PHP - Array_diff 具有两个不同维度的数组

问题描述 投票:0回答:2

我有这2个数组:

$haystack = array("rowid" => array("100", "200"), "description" => array ("something", "something else"));
$needle = array("rowid" => array("200", "300", "400"), "description" => array ("something else", "other", "other else"), "test" => "bye");

我想用 $needle 和 $haystack 进行 array_diff 但出现错误,因为 $needle 数组是多维的,但“test”键只有一维:

foreach ($needle as $key => $value) :
$left[$key] = array_diff($needle[$key],$haystack[$key]);
endforeach;

警告:array_diff():参数 #1 不是数组
警告: array_diff():参数 #2 不是数组

我该如何解决这个问题? 我需要在 $left 数组中仅维护“rowid”和“description”值(我可以丢弃“test”值)。

$left 应该是:

Array
(
    [rowid] => Array
        (
            [0] => 300
            [1] => 400
        )

    [description] => Array
        (
            [0] => other
            [1] => other else
        )

) 

谢谢您的帮助!

php arrays search multidimensional-array array-difference
2个回答
0
投票

删除“测试”=>“再见”;来自 $needle 或以正确的方式编写它们。

//array_diff takes arguments as array.
foreach ($needle as $key => $value) :
$left[$key] = array_diff($needle[$key],$haystack[$key]);
//when $key = test $needle[$key]=bye which is not array 
//thats why you got Warning: array_diff(): Argument #1 is not an array  this warning

//again when $key=test ,$haystack[$key]=null which is not array
//thats why you got Warning: array_diff(): Argument #2 is not an array
endforeach;

0
投票

如果要过滤的数组中的某项不是数组,或者在黑名单数组中找不到该键,则删除该行。使用两个数组时,修改输入行以包含

array_diff()
的过滤结果。 演示

$input = [
    "rowid" => ["200", "300", "400"],
    "description" => ["something else", "other", "other else"],
    "test" => "bye"
];
$blacklist = [
    "rowid" => ["100", "200"],
    "description" => ["something", "something else"]
];

$left = [];
foreach ($input as $key => $row) {
    if (is_array($row) && isset($blacklist[$key])) {
        $left[$key] = array_diff($row, $blacklist[$key]);
    }
}
var_export($left);

输出:

array (
  'rowid' => 
  array (
    1 => '300',
    2 => '400',
  ),
  'description' => 
  array (
    1 => 'other',
    2 => 'other else',
  ),
)

如果您需要索引子数组,请对过滤结果调用

array_values()

© www.soinside.com 2019 - 2024. All rights reserved.