将对象数组转换为关联数组

问题描述 投票:0回答:5

我用它来创建一个数组:

foreach ($results as $tire) {
    $group_price[] = array($tire->group, $tire->price);
}

我的结果是:

Array ( 
    [0] => Array (
        [0] => MAXAT 
        [1] => 118.91 
        ) 
    [1] => Array (
        [0] => FZSUV 
        [1] => 137.81 
    ) 
    [2] => Array ( 
        [0] => MAXAT 
        [1] => 153.79 
    )
)

我希望我的结果是:

Array (
    [0] => Array (
        [group] => MAXAT 
        [price] => 118.91
    )
    [1] => Array (
        [group] => FZSUV 
        [price] => 137.81
    )
    [2] => Array (
        [group] => MAXAT 
        [price] => 153.79
    )
)

我只是不确定如何改变我的 foreach 来改变输出。

php arrays foreach associative-array
5个回答
2
投票

像这样:

foreach($results as $tire){
    $group_price[] = array(
        'group' => $tire->group,
        'price' => $tire->price
    );
}

0
投票

尝试:

foreach($results as $tire){
            $group_price[] = array('group' => $tire->group,'price' => $tire->price);
        }

0
投票

就像这样:

foreach($results as $tire){
     $group_price[] = array(
                            'group' => $tire->group,
                            'price' => $tire->price
                           );
}

将键添加到数组元素,仅此而已。


0
投票
foreach($results as $tire){
            $group_price[] = array('group'=>$tire->group, 'price'=>$tire->price);
        }

0
投票

尝试

array('group' => $tire->group, 'price' => $tire->price);
© www.soinside.com 2019 - 2024. All rights reserved.