Ethelene Laverne
Ethelene Laverne

Reputation: 289

Convert Multidimensional Array to Single

I am using yii2 php framework and I have this query in 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 var_dump the $allUsers array, 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)

It's multidimensional array. I have searched and tried several solutions but they only give me this result:

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

Here are the few solutions I've tried but failed to 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 output is:

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

How do I make this work?

Upvotes: 5

Views: 1702

Answers (2)

Bashir ahmad
Bashir ahmad

Reputation: 241

More simple way you can convert it like this. use arrayHelper class and get the columns you want to get simply this way

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


});

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can simply iterate through the array and collect this data.
I just have 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; 
} 

Upvotes: 1

Related Questions