3

I need array keys in json array to be integers. Now they are strings. Could you tell me where is my mistake?

   $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
  • If your keys are strings how can they be converted to integers? Commented Apr 30, 2012 at 15:37
  • well thats the problem. Is there anyway to make cast them to int? Commented Apr 30, 2012 at 15:38

2 Answers 2

3

What you want is not possible with json_encode or json format

Look at this 2 arrays

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

Run

 var_dump($array,$array2);

Output

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)

You can see in PHP the are both Array

Now run

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

Output

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

Conclusion

If you are setting array keys and those keys does not start with 0 and increase serially it would be encoded as json object

If you want just arrays

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

Output

 string '["A","B","C","D"]' (length=17)
Sign up to request clarification or add additional context in comments.

Comments

2

The key in an object must be a string. If you want to not have strings then you must use sequential integer keys starting from 0, which will result in an array instead.

1 Comment

wasted bandwidth all those commas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.