3 回答
TA贡献1725条经验 获得超7个赞
我认为这就是您要寻找的......这也没有您的代码那么复杂。
<?php
$test_json= '{ "product": { "title": "Burton Custom Freestyle 151", "body_html": "<strong>Good snowboard!</strong>", "vendor": "Burton", "product_type": "Snowboard", "variants": [ { "option1": "Blue", "option2": "155" }, { "option1": "Black", "option2": "159" } ], "options": [ { "name": "Color", "values": [ "Blue", "Black" ] }, { "name": "Size", "values": [ "155", "159" ] } ] } }';
$test_product = json_decode($test_json);
$options = $test_product->product->options;
// Check whatever you like in this for each
foreach ($options as $option) {
// Example
switch ($option->name) {
case 'Color':
echo 'this is the color array';
break;
}
}
$options_json = json_encode($options);
var_dump($options_json);
?>
TA贡献1772条经验 获得超5个赞
如果我没有误解你的要求,那么你只需要这样做就可以得到你想要的,
<?php
$test_json= '{ "product": { "title": "Burton Custom Freestyle 151", "body_html": "<strong>Good snowboard!</strong>", "vendor": "Burton", "product_type": "Snowboard", "variants": [ { "option1": "Blue", "option2": "155" }, { "option1": "Black", "option2": "159" } ], "options": [ { "name": "Color", "values": [ "Blue", "Black" ] }, { "name": "Size", "values": [ "155", "159" ] } ] } }';
$test_product = json_decode($test_json, true);
$attributes2 = $test_product['product']['options'];
$expected = ['options'=>$attributes2];
echo json_encode($expected);
?>
演示: https: //3v4l.org/5r6WI
TA贡献1878条经验 获得超4个赞
您正在覆盖循环中的 name 键,您需要执行以下操作:
foreach ($attributes2 as $attribute) {
$data = [
"name" => $attribute["name"],
"values" => []
];
foreach ($attribute['values'] as $option) {
$data['values'][] = $option;
}
$options_arr[] = $data;
}
- 3 回答
- 0 关注
- 123 浏览
添加回答
举报