1

I have an array structure returned from a db laravel select that looks like this:

array:219 [▼
  0 => {#236 ▼
    +"mID": "101"
    +"qAVG": "6.44444"
  }
  1 => {#235 ▼
    +"mID": "102"
    +"qAVG": "4.15068"
  }

Apart from looping through the entire array and creating a new variable, is there a function in PHP that can generate something like this:

Array = array(
  101 => array(
           'qAVG' => 6.44444
            ),

  101 => array(
           'qAVG' => 4.15068
            )
)
1
  • No, it is impossible to have duplicate keys on the same level of an array. (101) Commented Oct 4, 2020 at 22:33

2 Answers 2

3

Yes there is a function for that array_column, which lets you extract a specific element from a multi-dimensional array and/or index the result by a specific element. So do both:

$result = array_column($array, 'qAVG', 'mID');

If the sub-arrays have more elements and you want them as well, then just re-index:

$result = array_column($array, null, 'mID');
Sign up to request clarification or add additional context in comments.

Comments

1

If you hadn't converted to an array in Laravel you could use the collection function pluck():

DB::table('foo')->select(['mID', 'qAVG'])->get()->pluck('qAVG', 'mID');

The first argument is what to pluck out, the second is what to use as the keys. It's great for populating a select dropdown with options.

Similar to the above comment, if you need the other columns:

DB::table('foo')->get()->keyBy('mID');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.