【问题标题】:PHP json_encode creates number index as string instead of an objectPHP json_encode 将数字索引创建为字符串而不是对象
【发布时间】:2017-04-11 23:46:34
【问题描述】:

我在 PHP 中有以下示例代码:

$data = array(
 'hello',
 'world',
 'hi'
);

$ret = array();
$ret['test'] = array();
$ret['testing'] = array();

foreach($data as $index => $value){
  if($index < 1){
      $ret['test'][$index]['val'] = $value;
      $ret['test'][$index]['me'] = 'index < 1';
  }
  else {
      $ret['testing'][$index]['val'] = $value;
      $ret['testing'][$index]['me'] = 'index >= 1';
  }
}

echo json_encode($ret);

我希望这是 JSON 输出:

[{
  "test":[
    {
       "val": "hello",
       "me": "index < 1"
    }
  ],
  "testing":[
    {
       "val": "world",
       "me": "index >= 1"   
    },
    {
       "val": "hi",
       "me": "index >= 1"
    }
  ]
}]

然而,最终发生的事情是我得到了以下结果:

[{
  "test":[
    {
       "val": "hello",
       "me": "index < 1"
    }
  ],
  "testing":{
    "1":{
       "val": "world",
       "me": "index >= 1"   
    },
    "2":{
       "val": "hi",
       "me": "index >= 1"
    }
  }
}]

"1""2" 键虽然是 int 并且尽管在使用相同的计数器变量时正确呈现了 test,但仍会出现。有没有办法确保testing 成为 JSON 对象数组?

【问题讨论】:

    标签: php json


    【解决方案1】:

    由于数组不是以索引0 开头而是以索引1 开头,因此它被编码为JSON 对象而不是JSON 数组。

    您可以使用array_values() 函数删除索引并仅保留值。

    例子:

    $ret['testing'] = array_values($ret['testing'])
    echo json_encode($ret);
    

    但是因为此时你不需要索引,你也可以将你的代码重构成这样:

    foreach($data as $index => $value){
      if($index < 1){
        $ret['test'][] = array(
          'val' => $value,
          'me' => 'index < 1'
        );
      }
      else {
        $ret['testing'][] = array(
          'val' => $value,
          'me' => 'index >= 1'
        );
      }
    }
    echo json_encode($ret);
    

    这样,数组将始终以索引0 开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多