1

我有一个看起来像这样的三维数组

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数组中取消它们。

谁能帮我实现这一目标?

4

4 回答 4

5
foreach($MyArray as $Key=>$group){
     foreach($group as $k=>$staff){ 
         if( !file_exists($staff['image'])) {
             unset($MyArray[$Key][$k]);
          }
     }
}

//你应该知道 $group 和 $staff 是临时变量

于 2013-07-26T14:06:39.130 回答
1
foreach ($MyArray as $Key=>$group) {

    foreach ($group as $k=>$staff) {

         if( empty($staff['image']) || !file_exists($staff['image'])) {
              unset($MyArray[$key][$k]);
         }

    }

}
于 2013-07-26T14:07:03.787 回答
0

条件应该是这样的。

foreach($MyArray as $Key=>&$group){            
    foreach($group as $staffkey=>$staff){
      if( $staff['image'] == null)) 
      {
        unset($MyArray[$key][$staffkey]);
      } 
    }
}
于 2013-07-26T14:10:02.720 回答
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");
 }
于 2013-07-26T14:14:08.450 回答