gpt4 book ai didi

php - 使用 array_diff 比较关联数组和数值数组

转载 作者:行者123 更新时间:2023-11-29 02:22:18 25 4
gpt4 key购买 nike

Array1 是一个关联数组,包含从 MySQL 中获取的多个列表,而 Array2 是一个数值数组,即一个简单的数组。 Array2有list_ids,用来过滤Array1。

Array1 示例:

Array (
[0] => Array (
[id] => 1
[list_id] => 68
[list_value] => List-68
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
[1] => Array (
[id] => 2
[list_id] => 69
[list_value] => List-69
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
[2] => Array (
[id] => 3
[list_id] => 80
[list_value] => List-80
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
[3] => Array (
[id] => 4
[list_id] => 81
[list_value] => List-81
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
)

数组 2:

[68, 81]

我的输出应该是:

Array (     
[0] => Array (
[id] => 2
[list_id] => 69
[list_value] => List-69
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
[1] => Array (
[id] => 3
[list_id] => 80
[list_value] => List-80
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
)

所以,一般情况下array_diff()会做,但是这里不行。我尝试将数值 Array2 转换为关联数组并使用 array_diff_assoc() 函数,但仍然无效。

我还尝试遍历我的数字数组并检查关联 Array1 中的每个元素(即从 MySQL 中获取的每个行)以获取数字数组中的每个数字。

foreach ($list as $val) {
while ( $r = mysqli_fetch_assoc($result)) {
echo $val."<br/>";
if($r['list_id'] != $val ) {
$new[] = $r;
}
}
}
print_r($new);

但输出仅回显数字 Array1 的第一个数字 4 次(Array1 的长度),因此只有一个 list_id 从关联 Array2 而不是 2 中移除:

68
68
68
68
Array (
[0] => Array (
[id] => 2
[list_id] => 69
[list_value] => List-69
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
[1] => Array (
[id] => 3
[list_id] => 80
[list_value] => List-80
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)
[2] => Array (
[id] => 4
[list_id] => 81
[list_value] => List-81
[subject] => "abc"
[message] => "abc"
[obj_var] => "abc"
[url_link] => "abc"
[list_time] => 2014-05-13 22:04:04
)

)

那么,我怎样才能让它发挥作用呢?最佳算法是什么?

最佳答案

您可以使用 foreach 循环和 in_array 检查来 unset 不需要的元素:

foreach ($Array1 as $key => $value)
if(in_array($valeu['list_id'], $Array2)) unset($list[$key]);

关于php - 使用 array_diff 比较关联数组和数值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29706352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com