[英]JavaScript array of objects broken out into PHP arrays
After several hours of Picasso coding ( my term ), I am stuck on how to efficiently convert this JavaScript array of objects into PHP (sent via AJAX). 经过数小时的毕加索编码(用我的术语 ),我陷入了如何有效地将对象的JavaScript数组转换为PHP(通过AJAX发送)的困境。
In JavaScript, the array of objects looks like this after JSON encoding: 在JavaScript中,JSON编码后的对象数组如下所示:
[
{"pid":"282","seller_id":"3","qty":"5"},
{"pid":"284","sn":"1234","seller_id":2,"qty":"1"},
{"pid":"284","sn":"2345","seller_id":2,"qty":"1"},
{"pid":"284","sn":"3456","seller_id":2,"qty":"1"},
{"pid":"111","sn":"987","seller_id":2,"qty":"1"}
]
There are two data groupings - note that the first transfer lacks a serial number and is to an external vendor, making it a sale. 有两个数据分组-请注意,第一个传输缺少序列号,并且是向外部供应商出售的。 The next 4 are all to "myself" (user is seller_id: 2), so these are internal transfers of product.
接下来的4个都属于“我自己”(用户是Seller_id:2),因此这些是产品的内部转让。
Anyway, the two types must be handled differently, so it would be immensely helpful if they were in separate arrays. 无论如何,这两种类型必须以不同的方式处理,因此,如果将它们放在单独的数组中会很有帮助。
Therefore, I wish to end up with two PHP arrays: 因此,我希望以两个PHP数组结束:
arrSale[0] = "pid":"282","seller_id":"3","qty":"5"
and 和
arrXfer[0] = "pid":"284","sn":"1234","seller_id":2,"qty":"1"
arrXfer[1] = "pid":"284","sn":"2345","seller_id":2,"qty":"1"
arrXfer[2] = "pid":"284","sn":"3456","seller_id":2,"qty":"1"
arrXfer[3] = "pid":"111","sn":"987","seller_id":2,"qty":"1"
I know that I must use $arrPHP = json_decode(jsonItems);
我知道我必须使用
$arrPHP = json_decode(jsonItems);
to decode the JSON, but what happens to the objects? 解码JSON,但是对象发生了什么? How would I break them into the two groups?
我如何将它们分为两组? I can't even find website resources that discuss this.
我什至找不到讨论此问题的网站资源。
Try this 尝试这个
$JSON = '[
{"pid":"282","seller_id":"3","qty":"5"},
{"pid":"284","sn":"1234","seller_id":2,"qty":"1"},
{"pid":"284","sn":"2345","seller_id":2,"qty":"1"},
{"pid":"284","sn":"3456","seller_id":2,"qty":"1"},
{"pid":"111","sn":"987","seller_id":2,"qty":"1"}
]';
$array = json_decode($JSON);
$arrSale = $arrXfer = array();
foreach($array as $obj)
if(isset($obj->sn)) $arrXfer[] = (array)$obj;
else $arrSale[] = (array)$obj;
print_r($arrSale);
print_r($arrXfer);
It gives us: 它给我们:
Array(
[0] => Array([pid] => 282[seller_id] => 3[qty] => 5)
)
Array(
[0] => Array([pid] => 284[sn] => 1234[seller_id] => 2[qty] => 1)
[1] => Array([pid] => 284[sn] => 2345[seller_id] => 2[qty] => 1)
[2] => Array([pid] => 284[sn] => 3456[seller_id] => 2[qty] => 1)
[3] => Array([pid] => 111[sn] => 987[seller_id] => 2[qty] => 1)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.