繁体   English   中英

PHP 如何将数组 json 字符串转换为数组?

[英]PHP How to convert array json string to array?

如何将 JSON 数组字符串转换为数组示例 - 这是数组 json 字符串 -

$params = [{"143":"166"},{"93":"49"}];

使用 json_decode 时

$options1 = json_decode($params, true);

但它返回

[super_attribute1] => Array
        (
            [0] => Array
                (
                    [143] => 166
                )

            [1] => Array
                (
                    [93] => 49
                )

        )

但我需要我们如何转换这种格式?

super_attribute] => Array
        (
            [143] => 163
            [93] => 49
        )

嵌套 foreach 可以为您解决这个问题

<?php

$data = [
    [ 143=>166 ],
    [ 93=>49 ]
];

$return = [];
foreach ($data as $d)
{
    foreach ($d as $k=>$v) $return[$k] = $v;
    unset($v);
} unset($d);

var_dump($return); // array(2) { [143]=> int(166) [93]=> int(49) }

只需使用循环或 map 来转换结果

function customJsonDecode($jsonString) {
    $decode = json_decode($jsonString, true);
    $result = [];
    foreach($decode as $item) $result = array_merge($result, array_pop($item));
    return $result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM