php动态创建数组并合并

我试图在foreach循环中动态创建未知数量的数组,最后将它们全部合并到一个数组中,并以 JSON 格式将其用于 Google Analytics。


到目前为止,我有以下代码在合并部分引发错误:


        $p=1;

        foreach(...){

        ...

        $arr = 'arr'.$p;

        $name = $order->ProductGroupName;

        $name = str_replace("'", "", $name);

        $arr = array(

            "name"=>$name,

            "id"=>$order->ProductCode,

            "price"=>$order->RRP,

            "quantity"=>$order->Quantity

        );

            $p++;       

        }

        for ($q = 1; $q<$p; $q++){

            $arry = 'arr'.$q;

            $merge = array_merge($arry, $merge);

        };

请问如何动态创建数组并在最后合并它们?我对 PHP 比较陌生,并且已经尽我所能让它工作。


哈士奇WWW
浏览 132回答 1
1回答

一只萌萌小番薯

我想我明白你想要做什么。只需动态追加[]到数组,您不需要合并:foreach($something as $order) {&nbsp; &nbsp; $arr[] = array (&nbsp; &nbsp; &nbsp; &nbsp; "name"=>str_replace("'", "", $order->ProductGroupName),&nbsp; &nbsp; &nbsp; &nbsp; "id"=>$order->ProductCode,&nbsp; &nbsp; &nbsp; &nbsp; "price"=>$order->RRP,&nbsp; &nbsp; &nbsp; &nbsp; "quantity"=>$order->Quantity&nbsp; &nbsp; );}如果您出于某种原因想要拥有字符串键,那么:$p = 1;foreach($something as $order) {&nbsp; &nbsp; $arr["SomeText$p"] = array (&nbsp; &nbsp; &nbsp; &nbsp; "name"=>str_replace("'", "", $order->ProductGroupName),&nbsp; &nbsp; &nbsp; &nbsp; "id"=>$order->ProductCode,&nbsp; &nbsp; &nbsp; &nbsp; "price"=>$order->RRP,&nbsp; &nbsp; &nbsp; &nbsp; "quantity"=>$order->Quantity&nbsp; &nbsp; );&nbsp; &nbsp; $p++;}就是这样。检查:print_r($arr);诸如变量变量的臭味(尽管没有正确完成)之类的东西$arry = 'arr'.$q;不应该使用。
打开App,查看更多内容
随时随地看视频慕课网APP