从基于公共ID的多维数组中获取多个数组

时间:2014-02-20 15:29:24

标签: php arrays sorting

我有一个大型数组,我想根据公共ID将其分组到其他数组中,这样我就可以使用array_splice来获取该ID的第一个和最后一个。

array( 
    [0] => array(id => 34, name = "walter"),
    [1] => array(id => 25, name = "walter jr"),
    [2] => array(id => 34, name = "saul"),
    [3] => array(id => 25, name = "jesse"),
    [4] => array(id => 25, name = "todd")
   )

我想要最终得到的是这样的。

array( 
    [0] => array(
                 id => 34, name = "walter",
                 id => 34, name = "saul"
                ),

    [1] => array(
                 id => 25, name = "walter jr",
                 id => 25, name = "jesse",
                 id => 25, name = "todd"
                 )
     )

我正在努力探索如何实现这一目标并且已经搜遍了所有人。我找到了一些使用array_unique和array_diff的解决方案,但我永远无法得到我正在寻找的结果。

2 个答案:

答案 0 :(得分:2)

您可以使用array_reduce对数组元素进行分组,请参见下文:

$data = array(
  0 => array('id' => 34, 'name' => "walter"),
  1 => array('id' => 25, 'name' => "walter jr"),
  2 => array('id' => 34, 'name' => "saul"),
  3 => array('id' => 25, 'name' => "jesse"),
  4 => array('id' => 25, 'name' => "todd")
);

$result = array_reduce($data, function ($result, $item){
  if (!isset($result[$item['id']])) {
        $result[$item['id']] = array();
  }
  $result[$item['id']][] = $item;
  return $result;
}, array());
print_r(array_values($result));

结果是:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 34
                    [name] => walter
                )

            [1] => Array
                (
                    [id] => 34
                    [name] => saul
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 25
                    [name] => walter jr
                )

            [1] => Array
                (
                    [id] => 25
                    [name] => jesse
                )

            [2] => Array
                (
                    [id] => 25
                    [name] => todd
                )

        )

)

答案 1 :(得分:0)

如果你想要密钥0,1,2,3,4 ...只需遍历整个阵列并覆盖密钥。 但是根据你正在做的事情,使用foreach来遍历没有密钥的数组。 = P

$all_array = array(
    0 => array( 'id' => 34 , 'name' => "walter" ) ,
    1 => array( 'id' => 25 , 'name' => "walter jr" ) ,
    2 => array( 'id' => 34 , 'name' => "saul" ) ,
    3 => array( 'id' => 25 , 'name' => "jesse" ) ,
    4 => array( 'id' => 25 , 'name' => "todd" )
) ;


$array_sort = array() ;

foreach ( $all_array as $piece_array ) {
    $array_sort[$piece_array['id']][] = $piece_array ;
}

ksort( $array_sort ) ;

var_dump( $array_sort ) ;