0

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

    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 );
}
4

1 回答 1

1

那将是这样的:

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

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

于 2013-01-08T19:29:46.437 回答