简体   繁体   English

如何在php中将json字符串转换为数组?

[英]how to convert json string to array in php?

I have a json format and want to convert this to my customized format. 我有一个json格式,想将此转换为我的自定义格式。 Please help me for this conversion using PHP. 请帮助我使用PHP进行此转换。 Please help me out, how can i construct the above mentioned JSON array format. 请帮帮我,我该如何构建上述JSON数组格式。 Here is my format: 这是我的格式:

 [{"label":"Food & Drinks","data":"2"},{"label":"Lifestyle","data":"1"}]

And want result in this format: 并想要这种格式的结果:

[["Food & Drinks", 2],["Lifestyle", 1]]

try below solution: 请尝试以下解决方案:

$json = '[{"label":"Food & Drinks","data":"2"},{"label":"Lifestyle","data":"1"}]';

$json_array = json_decode($json, true);

$new_array = array();

foreach($json_array as $arr){
    $new_array[] = array_values($arr);
}

print_r($new_array);

echo json_encode($new_array);

Output: 输出:

Array
(
    [0] => Array
        (
            [0] => Food & Drinks
            [1] => 2
        )

    [1] => Array
        (
            [0] => Lifestyle
            [1] => 1
        )

)
[["Food & Drinks","2"],["Lifestyle","1"]]

for more detail have alook at PHP: json_decode 有关更多详细信息,请查看PHP:json_decode

The solution is: 解决方案是:

So your code should be like this: 因此,您的代码应如下所示:

// suppose $json is your json string
$arr = json_decode($json, true);
$newArr = array_map('array_values', $arr);

// display $newArr array
var_dump($newArr);

Here $newArr is your desired array. $newArr是您所需的数组。

$array = json_decode($json, true);
$result = array();
for($i=0; $i<sizeof($array); $i++){
    $result[] = array_values($array[$i]);
}

$result will be your expected result $ result将是您的预期结果

Version that casts 'data' value to int 将“数据”值转换为int的版本

$json = '[{"label":"Food & Drinks","data":"2"},{"label":"Lifestyle","data":"1"}]';

$output = json_encode(array_map(function($v) {
    $v['data'] = (int) $v['data'];
    return array_values($v);
}, json_decode($json, true)));

// ["Food & Drinks",2],["Lifestyle",1]]
echo $output;

If int isn't needed 如果不需要int

$output = json_encode(array_map('array_values', json_decode($json, true)));

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

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