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

问题描述 投票:0回答:1

我有一个json,我需要获取特定的值,并使用foreach循环插入数组。然后我把它转换回json,检查是否得到相同的arrayjson格式或输出。但我不能让它工作。谁能帮助我,请。谢谢!

这是源格式。

enter image description here

但这是我在foreach循环中产生的结果:

enter image description here

这是我的代码.

$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);
php arrays multidimensional-array
1个回答
0
投票

我想这是你要找的...这也是你的代码没有那么复杂。

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

?>

0
投票

你在循环中覆盖了名称键,你需要做这样的事情。

foreach ($attributes2 as $attribute) {

    $data = [
        "name" => $attribute["name"],
        "values" => []
    ];


    foreach ($attribute['values'] as $option) {
        $data['values'][] = $option;
    }         

    $options_arr[] = $data;
}

0
投票

如果我没有理解错你的要求 那么你只需要这样做就可以得到你想要的东西了。

<?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.org5r6WI

© www.soinside.com 2019 - 2024. All rights reserved.