Daniel Suranyi
Daniel Suranyi

Reputation: 47

Nested array, get items with same key

I have a small tricky question with nested arrays. I am getting something like that from my database:

array
  0 => 
    array
      'id' => string '81' (length=2)
      'value' => string 'foobar' (length=6)
      'created_at' => string '2012-02-18 22:09:57' (length=19)
      'updated_at' => string '2012-02-18 22:09:57' (length=19)
  1 => 
    array
      'id' => string '106' (length=3)
      'value' => string 'barfoo' (length=6)
      'created_at' => string '2012-02-19 15:11:47' (length=19)
      'updated_at' => string '2012-02-19 15:11:48' (length=19)

What I want to achieve now is to extract a simple associative array, where one "column" becomes the key and one "column" becomes the value. For the case id / value, the result should then look like that:

array
  81 => 'foobar'
  106 => 'barfoo'

I know that I could do nested loops to foreach through all of the arrays, but I was wondering if there is a quicker and more native method. I was playing around with array_intersect, but it does not seem to deliver what I need.

Upvotes: 3

Views: 1460

Answers (1)

Ry-
Ry-

Reputation: 224886

Well, this one doesn't involve nested loops:

$result = array();

foreach($queryResult as $row) {
    $result[$row['id']] = $row['value'];
}

Upvotes: 5

Related Questions