按id查找并循环数组中的项目

时间:2014-12-12 09:51:12

标签: php arrays for-loop foreach

我有一个包含多个索引的数组,如

$arr = array(
   1 => array('id' => 0,
              'container' => 1
        ),
   2 => array('id' => 1,
              'container' => 1
        ),
   3 => array('id' => 2,
              'container' => 2
        ),
   4 => array('id' => 3,
              'container' => 1
        )
);

如何查找并循环容器为1的所有项目,然后循环所有容器为2的项目等等。

3 个答案:

答案 0 :(得分:1)

除了使用错误的数组赋值:。只需将其更改为=>

然后只使用foreach循环:

$containers = array(1, 2);
foreach($containers as $container) {
    foreach ($arr as $value) {
        if($container == $value['container']) {
            echo "Container: $container : ";
            echo $value['id'] . '<br/>';
        }
    }
}

答案 1 :(得分:0)

<?php
$arr = array(1 => array('id'=> 0, 'container'=> 1),
2 => array('id'=> 1, 'container'=> 1),
   3 => array('id'=> 2, 'container'=> 2),
   4 => array('id'=> 3, 'container'=> 1));
$temp = array();
foreach ($arr as $elem) {
 foreach ($elem as $k => $v) {
   if ($k == 'container') {
     $temp[$k][$v][] = $v;
   }
 }
}
print_r($temp);
?>

Working Example

答案 2 :(得分:0)

有很多方法可以做到这一点。这个通过给定的密钥重新构造/分组数组 - 如果你无论如何遍历所有元素,这是可行的。

<?php
$arr = array(
   1 => array('id' => 0,
              'container' => 1
        ),
   2 => array('id' => 1,
              'container' => 1
        ),
   3 => array('id' => 2,
              'container' => 2
        ),
   4 => array('id' => 3,
              'container' => 1
        )
);

$byContainer = groupBy($arr, 'container');
foreach($byContainer as $container=>$items) {
    echo $container, "\r\n";
    foreach($items as $e) {
        echo '  ', $e['id'], "\r\n";    
    }
}

function groupBy($arr, $key) {
    $result = array();
    foreach($arr as $e) {
        if ( !isset($result[ $e[$key] ]) ) {
            $result[ $e[$key] ] = array($e);
        }
        else {
            $result[ $e[$key] ][] = $e;
        }
    }
    return $result;
}