3v4l.org

run code in 200+ php & hhvm versions
<?php $directory = array ( '0' => (object) array ( 'dir_name' => 'Car', 'dir_id' => 'car' ), '1' => (object) array ( 'dir_name' => 'Bus', 'dir_id' => 'bus' ), '2' => (object) array ( 'dir_name' => 'Truck', 'dir_id' => 'truck' ) ); $subdirectory = array ( '0' =>(object) array ( 'sub_name' => 'Toyota', 'sub_id' => 'toyota', 'dir_id' => 'car' ), '1' =>(object) array ( 'sub_name' => 'Volvo', 'sub_id' => 'volvo', 'dir_id' => 'bus' ), ); $dataArray = array(); $parentfolder = array(); foreach( $subdirectory as $sub ) { $dirName = $sub->dir_id; if( !isset( $dataArray[$dirName] ) ) { $dataArray[$dirName] = array(); } $dataArray[$dirName][] = array('id' => $sub->sub_id, 'value' => $sub->sub_name); } foreach ($directory as $dir ) { $dirName = $dir->dir_id; if( isset ( $dataArray[$dirName] ) ) { $data = $dataArray[$dirName]; } else { $data = array(); } $parentfolder[] = array('id' => $dir->dir_id, 'value' => $dir->dir_name, 'data' => $data); } echo json_encode($parentfolder);
based on UmHWi
Output for 7.1.25 - 7.4.0alpha2
[{"id":"car","value":"Car","data":[{"id":"toyota","value":"Toyota"}]},{"id":"bus","value":"Bus","data":[{"id":"volvo","value":"Volvo"}]},{"id":"truck","value":"Truck","data":[]}]