How to combine objects to array without removing duplicates in PHP -
i have 3 objects , want them combine 1 array. there duplicate property names in objects, want them (with renames property name). how can that?
$object1 = { "id": "10", "unit_number": "12565" }, $object2 = { "id": "20", "full_name": "lorem ipsm" }, $object3 = { "id": "30", "phone": "123456789" }
i want output like,
array = ( "id1" => "10", "unit_number" => "12565", "id2" => "20", "full_name" => "lorem ipsm", "id3" => "30", "phone" => "123456789" );
i have tried assign them 1 array like,
$arr = array(); $arr['obj1'] = $object1; $arr['obj2'] = $object2; $arr['obj3'] = $object3;
now thought of doing foreach, stuck. actual object big. there many duplicates. not one.
i think can achieve using below code,
$object1 = (object) ['id' => '10', "unit_number"=> "12565", "name" => 'test name']; $object2 = (object) ['id' => '20', "full_name"=> "lorem ipsm"]; $object3 = (object) ['id' => '30', "phone"=> "123456789", "name" => "test name 1"]; $array1 = (array) $object1; $array2 = (array) $object2; $array3 = (array) $object3; function array_merge_dup_keys() { $arrays = func_get_args(); $data = array(); foreach ($arrays $a) { foreach ($a $k => $v) { $key1 = check_key_exists($k,$data); $data[$key1] = $v; } } return $data; } function check_key_exists($key,$array,$loop_count=1) { if(array_key_exists ( $key , $array )) { $val = explode('_',$key); $count = isset($val[1]) ? $val[1] : $loop_count; $start_key = isset($val[0]) ? $val[0] : $key; $key = $start_key.'_'.$loop_count; $key = check_key_exists($key,$array,$count+1); } return $key; } $data = array_merge_dup_keys($array1 ,$array2,$array3);
the output ($data) of above code be,
array ( [id] => 10 [unit_number] => 12565 [name] => test name [id_1] => 20 [full_name] => lorem ipsm [id_2] => 30 [phone] => 123456789 [name_1] => test name 1 )
Comments
Post a Comment