亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

foreach 返回為空

foreach 返回為空

PHP
大話西游666 2022-01-24 10:58:31
我對我正在做的循環有點懷疑,因為它返回的是空值。首先,我收到這樣的物品:$items = Session::get('items');$deco = json_decode($items, true);如果我回來,$deco我會得到這個:{ "items":[      {        "id":1,        "inventoryID":1,        "title":"Product 1",        "quantity":1,        "unit_price":20,        "image":"img.png"      },      {        "id":2,        "inventoryID":1,        "title":"Product2",        "quantity":1,        "unit_price":25,        "image":"img.png"       }    ]}現在,在循環中(我用它來更改一些鍵的值以集成貝寶)我有這個:$results = [];    foreach($deco['items'] as $element) {        $name=$element['title'];        $quantity=$element['quantity'];        $sku= $element['id'];        $price=$element['unit_price'];        $item = new Item();        $item -> setName($name)        ->setCurrency('USD')        ->setQuantity($quantity)        ->setSku($sku)         ->setPrice($price);        $results[]=$item;    }  如果我返回return $item(在循環外),我(如預期)只得到一個值,而不是所有集合:{"name": "Product2","currency": "USD","quantity": 1,"sku": 2,"price": "25"}但是,如果我返回return $results我需要的 var,它會給我這個(它會根據需要執行項目的 {},但返回空):[{},{}]整個代碼看起來像:public function test(){    $items = Session::get('items');    $deco = json_decode($items, true);    $results = [];    foreach($deco['items'] as $element) {        $name=$element['title'];        $quantity=$element['quantity'];        $sku= $element['id'];        $price=$element['unit_price'];        $item = new Item();        $item -> setName($name)        ->setCurrency('USD')        ->setQuantity($quantity)        ->setSku($sku)         ->setPrice($price);        $results[]=$item;    }      return $results;}
查看完整描述

2 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

它的發生僅是因為 JMS 序列化。我猜在控制器級別,您可能需要檢查是否已應用任何序列化組。


查看完整回答
反對 回復 2022-01-24
?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

答案(感謝 Ionica 在 discord 的 laravel 社區)是:


    $items = Session::get('items');

    $deco = json_decode($items,true);

    $itemList = new ItemList();


foreach($deco['items'] as $element) {


    $item = new Item();

    $item->setName($element['title'])

        ->setCurrency('USD')

        ->setQuantity($element['quantity'])

        ->setSku($element['id']) 

        ->setPrice($element['unit_price']);


    $itemList->addItem($item);

}


$arr = $itemList->toArray();

return $arr;


查看完整回答
反對 回復 2022-01-24
  • 2 回答
  • 0 關注
  • 199 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號