Convert PHP array to JSON tree -
i have got array in format:
array( array('id' => 1, 'parent_id' => null, 'name' => 'lorem ipsum'), array('id' => 2, 'parent_id' => 1, 'name' => 'lorem ipsum1'), array('id' => 3, 'parent_id' => 1, 'name' => 'lorem ipsum2'), array('id' => 4, 'parent_id' => 2, 'name' => 'lorem ipsum3'), array('id' => 5, 'parent_id' => 3, 'name' => 'lorem ipsum4'), array('id' => 6, 'parent_id' => null, 'name' => 'lorem ipsum5'), );
i have convert array json object style:
var json = { id: "1", name: "loreim ipsum", data: {}, children: [{ id: "2", name: "lorem ipsum1", data: {}, children: [{ id: "3", name: "lorem ipsum2", data: {}, children: [{ ..............
how can this? thanks.
my solution:
$data = array( array('id' => 1, 'parent_id' => null, 'name' => 'lorem ipsum'), array('id' => 2, 'parent_id' => 1, 'name' => 'lorem ipsum1'), array('id' => 3, 'parent_id' => 1, 'name' => 'lorem ipsum2'), array('id' => 4, 'parent_id' => 2, 'name' => 'lorem ipsum3'), array('id' => 5, 'parent_id' => 3, 'name' => 'lorem ipsum4'), array('id' => 6, 'parent_id' => null, 'name' => 'lorem ipsum5'), ); $itemsbyreference = array(); // build array of item references: foreach($data $key => &$item) { $itemsbyreference[$item['id']] = &$item; // children array: $itemsbyreference[$item['id']]['children'] = array(); // empty data class (so json_encode adds "data: {}" ) $itemsbyreference[$item['id']]['data'] = new stdclass(); } // set items children of relevant parent item. foreach($data $key => &$item) if($item['parent_id'] && isset($itemsbyreference[$item['parent_id']])) $itemsbyreference [$item['parent_id']]['children'][] = &$item; // remove items added parents elsewhere: foreach($data $key => &$item) { if($item['parent_id'] && isset($itemsbyreference[$item['parent_id']])) unset($data[$key]); } // encode: $json = json_encode($data);
Comments
Post a Comment