0

How to generate json response to jqtree with php ? I have tried with json_encode, but it leaves a lot of extra data. I was wondering if somebody had already forced this door.

How to achieve such structure:

var data = [
    {
        label: 'node1',
        children: [
            { label: 'child1' },
            { label: 'child2' }
        ]
    },
    {
        label: 'node2',
        children: [
        { label: 'child3' }
        ]
    }
];

form mysql id,parent,lable structure ?

Any help will be appreciated

  • 1
    That's not valid JSON. – Amal Murali Oct 15 '13 at 12:48
  • What is the relationship between nodes and chilidren? – Explosion Pills Oct 15 '13 at 13:04
  • Yes that's not JSON, but unfortunately this is the format. If we asume that id,parent,lable are columns in db, the relation is that "node1", "node2" are values of lable column and child1, child2 are rows with "node1" as parent. I am wondering if somebody have already written something that support this mess. – Rafał Wiatrowski Oct 15 '13 at 15:24

1 Answers1

1

The "extra data" in the json string is due to json_encode and associative array. If you try to json_encode and indexed array, you will obtain a so different json string, without that 'labels'.

However, jqtree needs a mixed json, with some 'string' keys and some 'index' keys.

Then, for obtain a valid json for jqtree in PHP, you should use the following function to your resulting array from the query, and after do a json_encode to the array this function returns:

    function arrayValuesRecursive($array)
    {
        $temp = array();
        foreach ($array as $key => $value) {
            if (is_numeric($key)) {
                $temp[] = is_array($value) ? arrayValuesRecursive($value) : $value;
            } else {
                $temp[$key] = is_array($value) ? arrayValuesRecursive($value) : $value;
            }
        }

        return $temp;
    }

For example:

$arrayFromQuery = array(...);
$arrayFromQuery = arrayValuesRecursive($arrayFromQuery);
$jqTreeJSON = json_encode($arrayFromQuery);