将数据推送到php中每个值的末尾

时间:2018-08-07 06:33:01

标签: php arrays

我有一些这样的数组

Array(
    [0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478"}
    [1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486"}
    [2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486"}
)

在这里,我想在每个循环的末尾添加一些数据,以便数据看起来如下。

Array(
    [0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478","variation_name"=>"tiles" ,"hsn" =>"42424"}
    [1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486","variation_name"=>"wood","hsn" =>"63636"}
    [2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486","variation_name"=>"granite","hsn" =>"66656"}
)

我尝试了数组推入方法,但是它创建了另一个索引,而不是向后添加新数据

下面是我的代码。

 $items = array();
        $variations = array();
        if ($purchaseOrderDetails->getOrderItems())
        {
            foreach ($purchaseOrderDetails->getOrderItems() as $key => $item)
            {
                $items[] = strval($item);

                  $variations[] = strval(new InventorySetVariation($item->getIsvid()));
            }
        }

        Utility::ajaxResponseTrue("", array("po" => strval($purchaseOrderDetails), "items" => $items, "variations" => $variations));

在这里,我想将项和变体合并为一个数组。

我该如何实现?

1 个答案:

答案 0 :(得分:2)

以下示例可以帮助您实现与您相似的目标

<?php
$items = array(
    0 => '{"puroriid":"3902598","purorid":"3901727","iid":"3927478"}',
    1 => '{"puroriid":"3902599","purorid":"3901727","iid":"3927486"}',
    2 => '{"puroriid":"3902600","purorid":"3901727","iid":"3927486"}'
); //Your Items

$itmesNew = [];
foreach($items as $val)
{
    $newItem = json_decode($val,true);
    $newItem['variation_name'] = 'test';    //New Items Append            
    $newItem['hsn'] = '123';                //New Items Append
    $itmesNew[] = json_encode($newItem);    //Add as json
}

echo "<pre>";
print_r($itmesNew);
?>

输出

Array
    (
        [0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478","variation_name":"test","hsn":"123"}
        [1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486","variation_name":"test","hsn":"123"}
        [2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486","variation_name":"test","hsn":"123"}
    )