0

If I have a multidimensional array containing data from certain mysql table, such as:

Array (
    [0] => Array (
        [0] => 5255071
        [id] => 5255071
        [1] => 2013-02-28 20:40:48
        [sent] => 2013-02-28 20:40:48
    )
    [1] => Array (
        [0] => 5253758
        [id] => 5253758
        [1] => 2010-11-16 12:56:39
        [sent] => 2010-11-16 12:56:39
    )
    [2] => Array (
        [0] => 5253517
        [id] => 5253517
        [1] => 2010-11-16 12:43:57
        [sent] => 2010-11-16 12:43:57
    )
    [3] => Array (
        [0] => 5252348
        [id] => 5252348
        [1] => 2010-11-16 11:19:35
        [sent] => 2010-11-16 11:19:35
    )
    ...
) 

Is there a way to create a new single array containing only the 'id' values? this is:

array(5255071, 5253758, 5253517, 5252348, ...)

The idea is to avoid using a foreach loop.

5
  • 2
    Why do you want to avoid a foreach loop when this is exactly the kind of thing it is used for... Commented Mar 1, 2013 at 14:58
  • your array doesn't make any sense. the end result would be something like $array['id'] = 103; $array['text'] = 'blah'; - you can't have multiple elements in the same key. Commented Mar 1, 2013 at 14:59
  • Could you show us the result of var_dump() of your array? Commented Mar 1, 2013 at 15:05
  • I don't think this is multidimensional array. It may be just array of associative arrays. Please show us your source array in some other way. Please print that array like this: print_r($array); and paste it. Commented Mar 1, 2013 at 15:16
  • Sorry, it is an array of associative arrays, yes, because it's the result from the MySQl query. Commented Mar 1, 2013 at 15:57

2 Answers 2

3

You could use array_map() for this:

function extractId ($array) { return $array['id']; }
$targetArray = array_map($sourceArray, "extractId");
Sign up to request clarification or add additional context in comments.

Comments

-1
$output = array_values($array['id']);

see: array_values

5 Comments

This assumes the array structure is like array('id' => array(...)) while apparently it is array(array('id' => ...), array('id' => ...)).
Is it? It's hard to tell from this notation. Wish we'd see an actual array instead of playing a guessing game :/
Well...looks like it to me anyway. Becaue it says array not $array...but you are right...my guess is as good as yours. ;)
This is not valid for an array of associative arrays, but thanks anyway. I want to avoid foreach because I must use native php functions whenever possible to avoid overloading the server, the array might be very large sometimes.
This answer is 100% incorrect. array_values() does not isolate column data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.