基于antoher对数组进行排序,如果不存在则添加键

时间:2016-10-10 16:09:43

标签: php arrays sorting

尝试使用$object['data']数组对$sort进行排序。问题是,如果对象中没有键,我想添加它并将其设置为0.

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

实际对象:

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

所需对象:

$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]
)];

我在循环中尝试使用array_key_exists,但实际上没有运气。

1 个答案:

答案 0 :(得分:0)

假设$object是您的原始数组,$sort是您想要操作原始数组的数组,解决方案将是这样的:

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);

这是live demo