PHP如何将数组推入数组[key]?

时间:2012-12-29 17:00:12

标签: php arrays sorting

这是我的代码:

$orders = Array();

foreach ($unassigned as $uorder) {
    $array = Array(
        "ordid"   => $uorder->idord,
        "fecha"   => $uorder->datorod,
        "cliente" => $uorder->idcli
    );

    array_push($orders[$uorder->user_id], $array);
}

print_r($orders);

结果如何:

Array (
    [vendor1] => 
    [vendor2] => 
)

我想做某种排序

所以我可以使用$orders[vendor1][0][ordid]来查找供应商的第一个订单。

2 个答案:

答案 0 :(得分:1)

您必须先将$orders[$uorder->user_id]指定为数组,否则将项目推送到其上是没有意义的。此外,您可以使用简写附加符号:

if(!isset($orders[$uorder->user_id]))
    $orders[$uorder->user_id] = array();
$orders[$uorder->user_id][] = $array;

答案 1 :(得分:0)

foreach循环中检查$orders[$uorder->user_id]是否为数组,如果不是则创建数组。

foreach($unassigned as $uorder):

    if(! is_array($orders[$uorder->user_id]))
        $orders[$uorder->user_id] = array();

    array_push($orders[$uorder->user_id],Array("ordid" => $uorder->idord, "fecha" =>  $uorder->datorod, "cliente" => $uorder->idcli));
endforeach;