PHP 重新编码 JSON 字符串为指定数组格式
可以使用 json_decode 函数将字符串解码为 PHP 数组,然后根据需要重新编码为所需的格式。下面是一个示例代码:
$str = '{\"2\": [11111, 11111111], \"3\": [22222, 2222222]}';
$arr = json_decode($str, true);
$data = array();
foreach ($arr as $key => $value) {
$data[] = array(
"user_id" => intval($key),
"u" => intval($value[0]),
"d" => intval($value[1])
);
}
$result = array("data" => $data);
$result_str = json_encode($result);
echo $result_str;
输出结果为:
{\"data\":[{\"user_id\":2,\"u\":11111,\"d\":11111111},{\"user_id\":3,\"u\":22222,\"d\":2222222}]}
注意:以上代码假设输入的字符串格式是固定的,即键值对中的值是一个数组,且数组中恰好有两个元素。如果输入的字符串格式可能有变化,需要根据实际情况进行适当的处理。
原文地址: https://www.cveoy.top/t/topic/qoZN 著作权归作者所有。请勿转载和采集!