查询数组到多维数组

时间:2018-05-22 05:11:03

标签: php codeigniter-3

所以我正在尝试运行查询,当我得到数组时,我想重新组织它。或者我可以运行查询来获得我想要的结果吗? 基本上我怎么能得到这个数组:

array() {
 [0] => array() {
  UID    => 1,
  gameid => 334613
 },
 [1] => array() {
  UID    => 2,
  gameid => 704234
 },
 [2] => array() {
  UID => 3,
  gameid => 704234
 }
}

成为这个:

$array = array (
    (334613) => array (
        [0] => 1
    ),
    (704234) => array (
        [0] => 2,
        [1] => 3
    )
);

2 个答案:

答案 0 :(得分:2)

您可以使用array_reduce

$arr = array(
    array(
      "UID"    => 1,
      "gameid" => 334613
    ),
    array(
      "UID"    => 2,
      "gameid" => 704234
    ),
    array(
      "UID" => 3,
      "gameid" => 704234
    )
);


$result = array_reduce($arr, function($c, $v){
    if( !isset( $c[ $v["gameid"] ] ) ) $c[ $v["gameid"] ] = array(); //Will also work without this line. 
    $c[ $v["gameid"] ][] = $v["UID"];       
    return $c;
}, array());

print_r( $result );

这将导致:

Array
(
    [334613] => Array
        (
            [0] => 1
        )

    [704234] => Array
        (
            [0] => 2
            [1] => 3
        )

)

Doc:array_reduce()

您还可以使用经典foreach

$result = array();
foreach( $arr as $key => $val ) {
    $result[ $val["gameid"] ][] = $val["UID"];  
} 

答案 1 :(得分:1)

简单的foreach循环将

$array = [ ... ]; // your array
$result = [];
foreach ($array as $game) {
    $result[ $game['gameid'] ][] = $game['UID'];
}

var_dump($result);