gpt4 book ai didi

JavaScript 对象数组分解为 PHP 数组

转载 作者:行者123 更新时间:2023-12-02 16:33:39 25 4
gpt4 key购买 nike

经过几个小时的毕加索编码(我的术语)后,我陷入了如何有效地将这个 JavaScript 对象数组转换为 PHP(通过 AJAX 发送)的问题。

在 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"}
]

有两个数据分组 - 请注意,第一次传输缺少序列号,并且传输给外部 vendor ,因此是一次销售。接下来的4个都是“我自己”(用户是seller_id:2),所以这些是产品的内部转移。

无论如何,这两种类型必须以不同的方式处理,因此如果它们位于单独的数组中将会非常有帮助。

因此,我希望最终得到两个 PHP 数组:

arrSale[0] = "pid":"282","seller_id":"3","qty":"5"

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"

我知道我必须使用 $arrPHP = json_decode(jsonItems); 来解码 JSON,但是对象会发生什么情况?我如何将他们分成两组?我什至找不到讨​​论此问题的网站资源。

最佳答案

试试这个

$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);

它给了我们:

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)
)

关于JavaScript 对象数组分解为 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com