3

我需要 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));
4

2 回答 2

2

json_encode使用或json格式无法实现您想要的

看看这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)
于 2012-04-30T15:41:30.097 回答
2

对象中的键必须是字符串。如果你不想有字符串,那么你必须使用从 0 开始的连续整数键,这将导致一个数组。

于 2012-04-30T15:43:43.993 回答