mchev mchev - 2 months ago 9
PHP Question

Sort an array based on antoher and add key if not exist

Trying to sort $object['data'] with the $sort array. The problem is, if a key doesn't exist in the object i would like to add it and set it to 0.

$sort = ['label1', 'label2', 'label3', 'label4', 'label5'] /* Could be everything */


Actual object:

$object = [ array(
"id"=>1,
"name"=>"john",
"data"=> ["label3"=>15, "label5"=>2]
), array(
"id"=> 2,
"name"=> "jane",
"data"=> ["label1"=> 8, "label2"=>9, "label5"=>3]
)];


Desired object:

$object = [ array(
"id"=>1,
"name"=>"john",
"data"=> ["label1"=>0, "label2"=>0, "label3"=>15, "label4"=>0, "label5"=>2]
), array(
"id"=> 2,
"name"=> "jane",
"data"=> ["label1"=>8, "label2"=>9, "label3"=>0, "label4"=>0, "label5"=>3]
)];


I tried with array_key_exists in loops but actually with no luck.

Answer

Suppose $object is your original array, and $sort is the array with which you want to manipulate the original array, the solution would be like this:

function mergeArrays($array1, $array2){
    $newArray = array();
    foreach($array1 as $v){
        if(!array_key_exists($v, $array2)){
            $newArray[$v] = 0; 
        }else{
            $newArray[$v] = $array2[$v]; 
        }
    }
    return $newArray;
}

foreach($object as $key => $array){
    $object[$key]['data'] = mergeArrays($sort, $array['data']);
}

// display $object array
var_dump($object);

Here's the live demo.