Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create new array from a multidimensional array [duplicate]

Tags:

php

I have this multidimensional array:

Array (
    [0] => Array ( 
        [id] => 1 
        [list_name] => List_Red
    ) 
    [1] => Array (
        [id] => 2
        [list_name] => List_Blue 
    )
)

...and i would like to create a new array containing only the [id]'s from it.

I would appreciate it alot if you guys could help me with that ^^

Thanks in advance.

like image 993
pitic Avatar asked Feb 08 '26 04:02

pitic


2 Answers

@fabrik Your solution indeed does work but it is also incorrect as PHP will throw a E_WARNING telling you that you're appending to an array that did not yet exist. Always initialise your variables before you use them.

$newList = array();
foreach($myList as $listItem) {
    $newList[$listItem['id']] = $listItem['list_name'];
}

This is now a list of all your list_names in the following format.

Array (
    1 => List_Red
    2 => List_Blue
)

Much easier for you to work with and you can now iterate over it like so..

foreach($newList as $itemID => $itemName) {
    echo "Item ID: $itemID - Item Name: $itemName<br>";
}
like image 180
Paul Dragoonis Avatar answered Feb 12 '26 05:02

Paul Dragoonis


You could use array_map like this:

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

That's assuming PHP 5.3, for PHP < 5.3 you have to use create_function:

$new_array = array_map( create_function( '$a', 'return $a["id"];' ), $orig_array );
like image 32
Muc Avatar answered Feb 12 '26 05:02

Muc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!