php将JSON数组键转换为整数

时间:2012-04-30 15:22:56

标签: php json

我需要json数组中的数组键为整数。现在他们是字符串。你能告诉我我的错误在哪里吗?

   $i = 0;
   while($i < 7) {
       isset($ips[date('d', $week_start + $i * 86400)])
           ? $ips[(int)date('d', $week_start + $i * 86400)] = count(date('d', $week_start + $i * 86400))
           : $ips[(int)date('d', $week_start + $i * 86400)] = 0;

       isset($time[date('d', $week_start + $i * 86400)])
           ? $time[(int)date('d', $week_start + $i * 86400)] = count(date('d', $week_start + $i * 86400))
           : $time[(int)date('d', $week_start + $i * 86400)] = 0;

       $i++;
   }

   return json_encode(array('unique' => $time, 'impressions' => $ips));

2 个答案:

答案 0 :(得分:2)

使用json_encodejson格式

无法实现您的目标

看看这2个阵列

$array = array("A","B","C","D");
$array2 = array(2=>"A",7=>"B",11=>"C",70=>"D");

运行

 var_dump($array,$array2);

输出

array
  0 => string 'A' (length=1)
  1 => string 'B' (length=1)
  2 => string 'C' (length=1)
  3 => string 'D' (length=1)
array
  2 => string 'A' (length=1)
  7 => string 'B' (length=1)
  11 => string 'C' (length=1)
  70 => string 'D' (length=1)

您可以在PHP中看到Array

现在运行

 var_dump(json_encode($array),json_encode($array2));

输出

string '["A","B","C","D"]' (length=17)
string '{"2":"A","7":"B","11":"C","70":"D"}' (length=35)

结论

如果您要设置数组键,并且这些键不以0开头并且按顺序增加,则会将其编码为json对象

如果你只想要数组

 var_dump(json_encode(array_values($array2)));

输出

 string '["A","B","C","D"]' (length=17)

答案 1 :(得分:2)

对象must be a string中的键。如果你想没有字符串,那么你必须使用从0开始的顺序整数键,这将导致一个数组。