Search code examples
phparraysjsonorgchart

Convert PHP Array to JSON Array of object


I'm using Google Orgchart in my project. In that I'm returning JSON OBJECT from PHP file.

Problem

My Problem is when I hardcode the value, It works fine. When I return data from PHP file. It did not work. I guess the data format which is returning from PHP file is not correct. File below.

$result = mysql_query("SELECT * FROM emp"); 
    while($row = mysql_fetch_array( $result )) {
        $arr1 = array(
            'v' => $row['name'],
            'f' => $row['name']+'<div style="color:red; font-style:italic">President</div>',
            '' => $row['rep'],
            '' => $row['des'],
        );
        array_push($dataarray, $arr1);
    }

echo json_encode($dataarray);

which returns object like below

enter image description here

How it Should be

My hardcorded JSON OBJECT below

   [
      [{v:'Prabhkar', f:'Prabhkar<div style="color:red; font-style:italic">President</div>'},
       '', 'The President'],
      [{v:'Raguram', f:'Raguram<div style="color:red; font-style:italic">GM</div>'},
       'Prabhkar', 'GM']
    ]

Console Screenshot below:

enter image description here

Do I need to create a one more array in PHP file. How I suppose to change the PHP array according to above screenshot. sorry for my english. Thank you.


Solution

  • You need to wrap 'v' and 'f' in a array, then push other values to parent array.

    $result = mysql_query("SELECT * FROM emp"); 
        while($row = mysql_fetch_array( $result )) {
            $arr1 = array(
                array(
                    'v' => $row['name'],
                    'f' => $row['name'] . '<div style="color:red; font-style:italic">President</div>'
                ),
                $row['rep'],
                $row['des']
            );
            array_push($dataarray, $arr1);
        }
    
    echo json_encode($dataarray);