如何从平面数组创建JavaScript多维数组

How to create a JavaScript multidimensional array from flat one?

本文关键字:数组 JavaScript 创建 平面      更新时间:2023-09-26

我有一个例子,我想改变一些值,这里的链接http://jsfiddle.net/k83hj1jb/

结果为平面数组:

[
    {"name":"options[11][140]","value":"140"},
    {"name":"options[8][99]","value":"99"},
    {"name":"options[8][103]","value":"103"}
]

我想改变一下:

[
    {
        "options":
        {
            "11":{"140":"140"},
            "8":
            {
                "99":"99",
                "103":"103"
            }
        }
    }
]

让我们将当前拥有的数组命名为flatArr和您想要的数组命名为nestArr

下面是如何从flatArr计算nestArr的:

var getNestArr = function (flatArr) {
    var nestObj = {'options': {}}, obj, opts, parts;
    for (i = 0; i < flatArr.length; i += 1) {
        obj = flatArr[i];
        opts = obj.name;
        parts = opts.replace('options[', '').slice(0, -1).split('][');
        if (!nestObj.options.hasOwnProperty(parts[0])) {
            nestObj.options[parts[0]] = {};
        }
        nestObj.options[parts[0]][parts[1]] = obj.value;
    }
    return [nestObj]; // returns an array instead of object.
};

测试:

var flatArr = [
    {"name":"options[11][140]","value":"140"},
    {"name":"options[8][99]","value":"99"},
    {"name":"options[8][103]","value":"103"}
];
var nestArr = getNestArr(flatArr);
console.log(JSON.stringify(nestArr));

输出为:

[{"options":{"8":{"99":"99","103":"103"},"11":{"140":"140"}}}] 

结果正是你想要的。虽然,您可能希望返回nestObj而不是[nestObj]

是的,你可以用PHP代替javascript:

// this is the start json
$json = '[{"name":"options[11][140]","value":"140"},
          {"name":"options[8][99]","value":"99"},
          {"name":"options[8][103]","value":"103"}]';
// decode the json to a php array
$array = json_decode($json, true);
// foreach value of the array
foreach ($array as $value) {
    // initialize a new array
    $option_value = array();
    // access to name value
    $option = $value["name"];
    // explode the string to an array where separator is the square bracket
    $option_values = explode("[", $option);
    // retrieve the two values between the options brackets removing the last square bracket
    $option_value[] = rtrim($option_values[1], "]");
    $option_value[] = rtrim($option_values[2], "]");
    // add a new array element in position of the first value of the option brackets: the array is composed by the second value and the value within the key "value"
    $new_array["options"][$option_value[0]][] = array($option_value[1], $value["value"]);
}
// at the end, encode it to the original json data
$json = json_encode($new_array);
// let show us the result on the screen
var_dump($json);

如果有任何疑问,或者如果我看起来你不太清楚,告诉我,我会修改我的答案