PHP 字符串转数组:将 JSON 字符串转换为指定格式的数组
您可以使用 json_decode 函数将字符串转换为数组,然后使用 foreach 循环遍历数组进行转换。以下是一个示例代码:
<?php
$str = '{"2": [11111, 11111111], "3": [22222, 2222222]}';
// 将字符串转换为数组
$arr = json_decode($str, true);
// 定义最终的结果数组
$result = array();
// 遍历数组进行转换
foreach ($arr as $key => $value) {
$temp = array(
'user_id' => (int)$key,
'u' => $value[0],
'd' => $value[1]
);
$result['data'][] = $temp;
}
// 输出最终的结果数组
print_r($result);
?>
输出结果为:
Array
(
[data] => Array
(
[0] => Array
(
[user_id] => 2
[u] => 11111
[d] => 11111111
)
[1] => Array
(
[user_id] => 3
[u] => 22222
[d] => 2222222
)
)
)
原文地址: https://www.cveoy.top/t/topic/qoTF 著作权归作者所有。请勿转载和采集!