检查键是否在另一个数组中,然后取值

时间:2019-01-26 22:54:26

标签: php

我正在尝试检查月份是否存在于另一个数组中,如果是,则从该数组中获取值。

月份数组

$months = array('01','02','03','04','05','06','07','08','09','10','11','12');

数据数组

$data = array("01"=>5,"02"=>2, "03"=>6.2, "11"=>10);

我的解决方案

$newArray = array();
    foreach($months as $mon){

        foreach($data as $key => $value){

            if(isset($data[$mon])){ 
               $newArray[$mon] = $value;
            }
            else{
                $newArray[$mon] = '0';
            }

        }
    } 

解决方案打印:

"response": {
        "10": "0",
        "11": 10,
        "12": "0",
        "01": 10,
        "02": 10,
        "03": 10,
        "04": "0",
        "05": "0",
        "06": "0",
        "07": "0",
        "08": "0",
        "09": "0"
    },
可以看到

一个响应,将值10分配给所有键。只能将其分配给键11,其他键的值应与数据数组中的值不同。“ 01” => 5,“ 02” => 2,“ 03” => 6.2

3 个答案:

答案 0 :(得分:1)

您不需要遍历数据数组,只需要检查它是否在$ data数组中设置:

$newArray = array();
foreach($months as $mon){
   $newArray[$mon] = (isset($data[$mon]) ? $data[$mon] : '0'); 
}

答案 1 :(得分:0)

如果我了解您的需求,则可以使用array_reduce

$result = array_reduce($months, function ($result, $month) use ($data) {
  $result[$month] = $data[$month] ?? 0;
  return $result;
}, []);

演示:https://3v4l.org/WCIId

答案 2 :(得分:0)

这是越野车的一部分:

考虑当前的$mon01,而$key $value对是"11"=>10

if(isset($data[$mon])){        // $data[$mon] is set (this is $data["01"])
    $newArray[$mon] = $value;  //$value = 10 actually. It sets the wrong value to $newArray["01"]

您不需要该内循环,因为您可以检查$data[$mon]并使用它而不是$value

$months = array('01','02','03','04','05','06','07','08','09','10','11','12');
$data = array("01"=>5,"02"=>2, "03"=>6.2, "11"=>10);

$newArray = array();
foreach($months as $mon)
{
    if(isset($data[$mon])){ 
       $newArray[$mon] = $data[$mon];
    }
    else{
        $newArray[$mon] = '0';
    }
} 

var_dump($newArray);

输出

array (size=12)
  '01' => int 5
  '02' => int 2
  '03' => float 6.2
  '04' => string '0' (length=1)
  '05' => string '0' (length=1)
  '06' => string '0' (length=1)
  '07' => string '0' (length=1)
  '08' => string '0' (length=1)
  '09' => string '0' (length=1)
  10 => string '0' (length=1)
  11 => int 10
  12 => string '0' (length=1)