1

I have the following array returned by my script.

Array
(
    [0] => Array
        (
            [id] => 67
        )

    [1] => Array
        (
            [id] => 68
        )

    [2] => Array
        (
            [id] => 69
        )

    [3] => Array
        (
            [id] => 70
        )

)

How can I convert it to:

Array
(
    [0] => 67

    [1] => 68

    [2] => 69

    [3] => 70
)

I'm only interested in the IDs returned.

4 Answers 4

3

array_map() is one possibility since it accumulates any value returned by the callback into its returned array. The callback then just needs to return the id :

$flat = array_map(function($a) {return $a['id'];}, $orig_array);

The above requires PHP 5.3+, since it uses an anonymous function, but the same can be achieved with a named function passed as a string to array_map().

Otherwise, a foreach loop is pretty conventional and can preserve the original keys had then been non-sequential.

$flat = array();
foreach ($orig_array as $key => $a) {
  $flat[$key] = $a['id'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

@chris there is no built-in array_pluck() tmk. Lots of examples on how to make them though.
1

I have not tested this function, but try this suggestion: http://www.php.net/manual/en/function.array-values.php#104184

Comments

1
$temp = call_user_func_array('array_merge_recursive', $arr);
$final = $temp['id'];
print_r($final);

Why that works is tricky. Honestly, just use a foreach loop.

Comments

1

Continuing @Mickael's answer, you can also use array_walk() function:

function format(&$item, $key) {
    $item = $item["id"];
}

array_walk($arr, "format");

Or in one line with lambda function:

array_walk($arr, create_function('&$item, $key', '$item = $item["id"];'));

It works with your array directly, hence we can easily call it "array converting".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.