如何使用foreach将array1的值获取到array2

时间:2019-06-27 15:07:28

标签: php arrays

我希望如果数组1与数组2的值不同,它将返回到false

数组1:

$array1 = [
    "sports" => "volleyball"
    "another" => [
      "sports" => "basketball"
      "another" => [
        "sports" => "football"
      ]
    ]
  ];

数组2:

$array2 =  [
  0 => "volleyball"
  1 => "basketball"
  2 => "football"
];

我尝试了array_search(),而array_intersect对我没有用。

1 个答案:

答案 0 :(得分:1)

您可以使用array_walk_recursive以array2的格式构建array1,然后应用array_diff

$array1 = [
  "sports" => "volleyball",
  "another" => [
    "sports" => "basketball",
    "another" => [
      "sports" => "football"
    ]
  ]
 ];

$array2 =  [
  0  => "volleyball",
  1 => "basketball",
  2 => "football"
];
$arr1 = [];
array_walk_recursive($array1, function($v, $k) use (&$arr1){
    $arr1[] = $v;
});
$diff = array_diff($arr1, $array2);
echo count($diff) > 0 ? true : false;