dongwu4834 2015-06-22 12:53
浏览 77

json_decode - 强制数组键为字符串

Take a look at the following code:

$a = json_decode('{"0":"xy"}', true);

This will return an associative array like [0 => "xy"].

Is there a way not to automatically convert the keys to numbers? The result I'd like to have would be the array ["0" => "xy"] with strings as keys exclusively.

  • 写回答

2条回答 默认 最新

  • duanpen9294 2015-06-22 13:03
    关注

    Not really sure why you would want numerical array keys to be strings. It can make life harder when trying to search through an array by key or rekey the array.

    However, if you really want your keys to be strings this should help

    $array = json_decode('{"0":"xy"}', true);
    foreach($array as $key => $value) { 
       $newArray[(string) $key] = $value;
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能