我有一个看起来像这样的三维数组
Array(
[Group 1] => Array
(
[0] => Array
(
[category] => Group1
[firstname] => John
[lastname] => Johns
[image] => /mysite.etc/jj.jpg
)
[1] => Array
(
[category] => Group1
[firstname] => John
[lastname] => James
[image] => /mysite.etc/jj2.jpg
)
)
[Group 2] => Array
(
[0] => Array
(
[category] => Group2
[firstname] => John
[lastname] => Jackson
[image] => NULL
)
[1] => Array
(
[category] => Group2
[firstname] => John
[lastname] => Jimson
[image] => /mysite.etc/jj4.jpg
)
)...etc)
我正在尝试遍历数组并删除people
单元格中没有值的任何[image]
(即数组的第二级)。
我试过
foreach($MyArray as $Key=>&$group){
foreach($group as &$staff){
if(!file_exists($staff['image'])){
unset($staff);
}
}
}
但这不会删除没有图像的数组项。循环正确地识别没有图像的人员,好像我包含一些代码以将它们回显到页面上,这是有效的。它只是没有从$MyArray
数组中取消它们。
任何人都可以帮助我实现这个目标吗?
答案 0 :(得分:5)
foreach($MyArray as $Key=>$group){
foreach($group as $k=>$staff){
if( !file_exists($staff['image'])) {
unset($MyArray[$Key][$k]);
}
}
}
//你应该知道$ group和$ staff是临时变量
答案 1 :(得分:1)
foreach ($MyArray as $Key=>$group) {
foreach ($group as $k=>$staff) {
if( empty($staff['image']) || !file_exists($staff['image'])) {
unset($MyArray[$key][$k]);
}
}
}
答案 2 :(得分:0)
条件应该是这样的。
foreach($MyArray as $Key=>&$group){
foreach($group as $staffkey=>$staff){
if( $staff['image'] == null))
{
unset($MyArray[$key][$staffkey]);
}
}
}
答案 3 :(得分:0)
你可以使用array_filter:
有一个闭包:在php 5.3中可用
foreach($groups as &$users){
$users = array_filter($users, function ($a) { return isset($a["image"]) && file_exists($a["image"]); });
}
没有闭包
function hasImage($a){ return isset($a["image"]) && file_exists($a["image"]); }
foreach($groups as &$users){
$users = array_filter($users, "hasImage");
}