为了账号安全,请及时绑定邮箱和手机立即绑定

使用循环php在多维数组上添加项目

使用循环php在多维数组上添加项目

PHP
元芳怎么了 2023-04-15 14:28:26
我有一个 json,我需要获取特定值并使用 foreach 循环插入到数组中。然后我将它转换回 json 以检查我是否得到相同的数组/json 格式或输出。但我无法让它发挥作用。有人能帮助我吗。谢谢!这是源格式:但这是我在 foreach 循环中生成的内容:这是我的代码。$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'];$options_arr = array();foreach ($attributes2 as $attribute) {$options_arr['name'] = $attribute['name'];    foreach ($attribute['values'] as $option) {        $options_arr['values'][] = $option;    }         }$options_json = json_encode($options_arr);var_dump($options_json);
查看完整描述

3 回答

?
qq_遁去的一_1

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


?>


查看完整回答
反对 回复 2023-04-15
?
月关宝盒

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


查看完整回答
反对 回复 2023-04-15
?
UYOU

TA贡献1878条经验 获得超4个赞

您正在覆盖循环中的 name 键,您需要执行以下操作:


foreach ($attributes2 as $attribute) {


    $data = [

        "name" => $attribute["name"],

        "values" => []

    ];



    foreach ($attribute['values'] as $option) {

        $data['values'][] = $option;

    }         


    $options_arr[] = $data;

}


查看完整回答
反对 回复 2023-04-15
  • 3 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信