基于php

时间:2018-02-15 12:59:03

标签: php multidimensional-array

$arr1 = [
    ["label" => "January", "value" => "0"],
    ["label" => "February", "value" => "0"],
    ["label" => "March", "value" => "0"],
    ["label" => "April", "value" => "0"],
    ["label" => "May", "value" => "0"],
    ["label" => "June", "value" => "0"],
    ["label" => "July", "value" => "0"],
    ["label" => "August", "value" => "0"],
    ["label" => "September", "value" => "0"],
    ["label" => "October", "value" => "0"],
    ["label" => "November", "value" => "0"],
    ["label" => "December", "value" => "0"]
];

$arr2 = [
    ["label" => "January", "value" => "20"],
    ["label" => "March", "value" => "30"],
    ["label" => "April", "value" => "24"],
    ["label" => "May", "value" => "10"],
    ["label" => "July", "value" => "0"],
    ["label" => "November", "value" => "34"]
];

我想结合这两个数组值,应该替换为“0”

1 个答案:

答案 0 :(得分:4)

想看看一些阵列功能MAGIC?!? (Demo

var_export(
    array_values(  // remove temporary keys
        array_replace_recursive(  // replace first array values with second
            array_column($arr1,NULL,'label'),  // assign temporary keys using label values
            array_column($arr2,NULL,'label')   // assign temporary keys using label values
        )
    )
);

或者,您可以使用它来获得相同的结果:(Demo

$arr1=array_column($arr1,NULL,'label');  // temporary keys
foreach($arr2 as $row){  // loop only the new values
    $arr1[$row['label']]['value']=$row['value'];  // assign new values
}
var_export(array_values($arr1));  // remove temporary keys and print to screen

输出:

array (
  0 => 
  array (
    'label' => 'January',
    'value' => '20',
  ),
  1 => 
  array (
    'label' => 'February',
    'value' => '0',
  ),
  2 => 
  array (
    'label' => 'March',
    'value' => '30',
  ),
  3 => 
  array (
    'label' => 'April',
    'value' => '24',
  ),
  4 => 
  array (
    'label' => 'May',
    'value' => '10',
  ),
  5 => 
  array (
    'label' => 'June',
    'value' => '0',
  ),
  6 => 
  array (
    'label' => 'July',
    'value' => '0',
  ),
  7 => 
  array (
    'label' => 'August',
    'value' => '0',
  ),
  8 => 
  array (
    'label' => 'September',
    'value' => '0',
  ),
  9 => 
  array (
    'label' => 'October',
    'value' => '0',
  ),
  10 => 
  array (
    'label' => 'November',
    'value' => '34',
  ),
  11 => 
  array (
    'label' => 'December',
    'value' => '0',
  ),
)