Convert a multidimensional array to a single

I am using yii2 php framework and I have this request when accessing all users in db:

$allUsersQuery = new Query;
$allUsersQuery->select(['_id'])->from('user')->where([ 'parent' => new \MongoId($session['company_owner']) ]);
$allUsers = $allUsersQuery->all(); 

When I am an var_dumparray $allUsers, it gives me this output:

array (size=5)
  0 => 
    array (size=1)
      '_id' => 
        object(MongoId)[147]
          public '$id' => string '55d5a227650fc90c35000044' (length=24)
  1 => 
    array (size=1)
      '_id' => 
        object(MongoId)[148]
          public '$id' => string '55d5a22a650fc90c35000047' (length=24)
  2 => 
    array (size=1)
      '_id' => 
        object(MongoId)[149]
          public '$id' => string '55d5a22a650fc90c3500004a' (length=24)
  3 => 
    array (size=1)
      '_id' => 
        object(MongoId)[150]
          public '$id' => string '55d5a22b650fc90c3500004d' (length=24)
  4 => 
    array (size=1)
      '_id' => 
        object(MongoId)[151]
          public '$id' => string '55d5a22b650fc90c35000050' (length=24)

This is a multidimensional array. I searched and tried several solutions, but they gave me this result:

array (size=1)
  '_id' => 
    object(MongoId)[147]
      public '$id' => string '55d5a227650fc90c35000044' (length=24)

Here are some solutions that I tried but could not work:
1.

function array_flatten($allUsers) { 
    if (!is_array($allUsers)) { 
        return FALSE; 
    } 
    $allUsersResult = array(); 
    foreach ($allUsers as $key => $value) { 
        if (is_array($value)) { 
            $allUsersResult = array_merge($allUsersResult, array_flatten($value)); 
        } 
        else { 
          $allUsersResult[$key] = $value; 
        } 
    } 
    return $allUsersResult; 
} 

2.

array_reduce($allUsers, 'array_merge', array());

3.

$allUsers = $allUsers[0];

My expected result:

Array('value1', 'value2', 'value3');

How do I do this job?

+4
source share
2 answers

You can just iterate over the array and collect this data.
I just edited your function:

function array_flatten($allUsers) { 
    if (!is_array($allUsers)) { return FALSE; } 

    $allUsersResult = array(); 
    foreach ($allUsers as $key => $value) { 
        if (!is_array($value)) { return FALSE; } 

        $allUsersResult[] = $value["_id"]->{'$id'};
    } 
    return $allUsersResult; 
} 
+1
source

. arrayHelper , .

$array = [
    ['id' => '123', 'data' => 'abc'],
    ['id' => '345', 'data' => 'def'],
];
$result = ArrayHelper::getColumn($array, 'id');


});
0

Source: https://habr.com/ru/post/1611703/


All Articles