【问题标题】:PHP How to convert array json string to array?PHP如何将数组json字符串转换为数组?
【发布时间】:2021-03-11 13:52:11
【问题描述】:

如何将 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
        )

【问题讨论】:

  • 您展示的示例与您得到的结果不符。
  • super_attribute] => Array 看起来不是一个有效的结果 - 请分享更多详细信息

标签: php arrays indexing associative-array


【解决方案1】:

嵌套 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) }

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多