创建新密钥=>现有数组中的值对

时间:2013-01-08 19:28:10

标签: php arrays

我有一个看起来像这样的数组:

    Array
(
    [0] => stdClass Object
        (
            [food] => Pizza
            [music] => Rock
            [color] => blue
            [name] => John
        )

    [1] => stdClass Object
        (
            [food] => Toast
            [music] => Jazz
            [color] => yellow
            [name] => Greg
        )

    [2] => stdClass Object
        (
            [food] => Steak
            [music] => Classical
            [color] => green
            [name] => Steve
        )

    [3] => stdClass Object
        (
            [food] => Cake
            [music] => Blues
            [color] => red
            [name] => Peter
        )

)

如何创建一个新数组,我将部分内容合并到新的key => value对,例如Peter => Cake

我已设法使用某些值,但它们未连接到键:

$myArr = *The array posted above*
$newArray = array();

foreach ( $myArr as $arr ) {
    array_push( $newArray, $arr->food );
}

1 个答案:

答案 0 :(得分:1)

这就像是:

$newArray = array();
foreach ( $myArr as $arr ) {
    $newArray[$arr->name] = $arr->food;
}

请注意,重复的名称会被最后一次出现覆盖。