2016-08-09 13 views
0

(json_encoded)は次のようになります[PHP]インクリメント値ネストされたオブジェクトの内部

私は$カートオブジェクトを持っていること:

{"merchant_id":"5","items":[{"id":"23”,”size”:”small”,”price":"3","quantity”:1},{"id":"23”,”size":" 
large","price":"3","quantity”:1},{"id":"24”,”size”:”medium”,”price":"3","quantity":1}]} 

私はid=23を持っているアイテムの数量をインクリメントしたいのですがそしてsize=largeは、その特定の値を識別し、すべてのアイテムをループしたり、オブジェクトを再作成することなくそれを増やすエレガントな方法はありますか?

ありがとうございました!

+3

簡単な答えNO – RiggsFolly

+0

オブジェクトを再作成せずに何を意味するのですか? json_decodeを使用していませんか? – Whiteulver

答えて

1

ルーピングなしで、フィルタリングを使用して、希望要素を選択できます。

を使用し、objectsとしてデータを取得すると、参考になる場合がありますので、arrayとしてください。

例では、次の

<?php 

$json = '{ 
    "merchant_id": "5", 
    "items": [{ 
     "id": "23", 
     "size": "small", 
     "price": "3", 
     "quantity": 1 
    }, { 
     "id": "23", 
     "size": "large", 
     "price": "3", 
     "quantity": 1 
    }, { 
     "id": "24", 
     "size": "medium", 
     "price": "3", 
     "quantity": 1 
    }] 
}'; 

$cart = json_decode($json); # Decode as stdClass objects 

# Filter desire element 
$item = array_filter($cart->items, function ($i) { 
    return $i->id == "23" && $i->size == 'large'; 
}); 

# array_filter returns array so get the first element. 
# you could check if $item is false. 
$item = reset($item); 
# increase quantity 
$item->quantity++; 

# Encode json data 
$json = json_encode($cart); 

echo $json; 
+0

完璧な解決策は、それが元のオブジェクトを更新するだろうか分からなかった! –

0

私はそうは思わない。あなたはjson_decode、私はあなたを持つアイテム更新したいIDを探して、各項目を反復処理さを考え出すことができる最善の方法を使用と仮定

は、アップデートを実行し、ループ破る:

foreach($cart['items'] as $k => $item){ 
    if($item['id'] == 23){ 
     $cart['items'][$k]['quantity']++; 
     break; 
    } 

    continue; 
} 

と仮定しjson_decodeを使いたくない場合は、preg_replaceを使うことができますが、正直言ってあなたが求めている優雅さはありません。

関連する問題