1

So I'm trying to run a query and when I get the array, I want to reorganize it. Or can I possibly run a query to get the result that I want? Basically how can I get this array:

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

to become this:

$array = array (
    (334613) => array (
        [0] => 1
    ),
    (704234) => array (
        [0] => 2,
        [1] => 3
    )
);
1
  • add your code here Commented May 22, 2018 at 5:17

2 Answers 2

2

You can use 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 );

This will result to:

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

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

)

Doc: array_reduce()

You can also use the classic foreach

$result = array();
foreach( $arr as $key => $val ) {
    $result[ $val["gameid"] ][] = $val["UID"];  
} 
Sign up to request clarification or add additional context in comments.

Comments

1

Simple foreach loop will do

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

var_dump($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.