简体   繁体   English

从多维数组创建新数组

[英]create new array from a multidimensional array

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. ...并且我想创建一个仅包含[id]的新数组。

I would appreciate it alot if you guys could help me with that ^^ 如果你们能帮助我,我会非常感激的^^

Thanks in advance. 提前致谢。

@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. @fabrik您的解决方案确实可以工作,但是它也不正确,因为PHP会抛出E_WARNING消息,告诉您要追加到尚不存在的数组。 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. 现在,以以下格式列出了所有list_names。

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>";
}
foreach($array as $label => $data)
{
    $final[] = $data['id'];
}

You could use array_map like this: 您可以这样使用array_map

$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: 假设PHP 5.3,对于PHP <5.3,您必须使用create_function:

$new_array = array_map( create_function( '$a', 'return $a["id"];' ), $orig_array );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM