如何删除数组中除特定项目以外的所有项目? [英] How to remove all items of array except specific one?
本文介绍了如何删除数组中除特定项目以外的所有项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含这些嵌套数组的变量:
I have a variable which is containing these nested arrays:
echo $var;
/* Output:
Array(
[0] => Array
(
[id] => 1
[box] => 0
)
[2] => Array
(
[id] => 2
[box] => 0
)
[3] => Array
(
[id] => 3
[box] => 1
)
) */
现在,我想删除上面数组中除 $ numb = 2;
(id的值)以外的所有项.我的意思是我想要这个输出:
Now I want to remove all items of array above except $numb = 2;
(the value of id). I mean I want this output:
echo newvar;
/* Output:
Array(
[2] => Array
(
[id] => 2
[box] => 0
)
) */
我该怎么做?
实际上,我可以使用 if
语句和 array_shift()
函数来完成其中的一部分:
Actually I can do a part of it by using if
statement and array_shift()
function:
foreach($var as $key => $val) {
if($val["id"] != 2) {
array_shift($var);
}
}
但是上面的代码输出不需要我.
But the output of code above isn't want I need.
推荐答案
您可以使用略有不同的循环.
You can use a slightly different loop.
foreach ($var as $item) {
if ($item['id'] == 2) {
$newvar = $item;
break;
}
}
您还可以使用array_filter
You could also use array_filter
$id = 2;
$newvar = array_filter($var, function($x) use ($id) { return $x['id'] == $id; });
但是它很可能效率较低,因为它必须检查数组的每个元素.
but it would most likely be less efficient as it would have to check every element of the array.
这篇关于如何删除数组中除特定项目以外的所有项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文