How do I `json_encode()` keys from PHP array? - php

I have an array which prints like this
Array ( [0] => 1691864 [1] => 7944458 [2] => 9274078 [3] => 1062072 [4] => 8625335 [5] => 8255371 [6] => 5476104 [7] => 6145446 [8] => 7525604 [9] => 5947143 )
If I json_encode($thearray) I get something like this
[1691864,7944458,9274078,1062072,8625335,8255371,5476104,6145446,7525604,5947143]
Why the name is not encoded (e.g 0, 1 , 2 , 3 etc) ? and how should I do to make it appear in the json code?
the full code is below
$ie = 0;
while($ie 10)
{
$genid = rand(1000000,9999999);
$temp[$ie] = $genid ;
$ie++;
}
print_r($temp);
$temp_json = json_encode($temp);
print_r($temp_json);

You can force that json_encode uses an object although you’re passing an array with numeric keys by setting the JSON_FORCE_OBJECT option:
json_encode($thearray, JSON_FORCE_OBJECT)
Then the returned value will be a JSON object with numeric keys:
{"0":1691864,"1":7944458,"2":9274078,"3":1062072,"4":8625335,"5":8255371,"6":5476104,"7":6145446,"8":7525604,"9":5947143}
But you should only do this if an object is really required.

Use this instead:
json_encode((object)$temp)
This converts the array into object, which when JSON-encoded, will display the keys.
If you are storing a sequence of data, not a mapping from number to another number, you really should use array.

Because those are just the indices of the array. If you want to add some kind of name to each element then you need to use an associative array.
When you decode that JSON array though it will come back out to 0, 1, 2, 3 etc.

This is defined behaviour. The array you show is a non-associative, normally indexed array. Its indexes are implicitly numeric.
If you decode the array in PHP or JavaScript, you will be able to access the elements using the index:
$temp_array = json_decode($temp_json);
echo $temp_array[2]; // 9274078

Related

PHP - Store an array returned by a function in an already existing array, one by one

Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

PHP json_encode switching array to object in a particular server... why?

I have a library that read a directory and join a lot of information in a single object, so I can get it by JSON and work on it with JavaScript. I have a php that calls the lib for me and returns the JSON, simple as this:
echo('&vars_ini=OK&dados='.json_encode($Lista).'&vars_fim=');
After get the value of "dados", this is what I got:
{"erro":"OK","Lista":[{"nome":"a-process.gif","base":"a-process","ext":"gif","bytes":93117,"datac":"07\/04\/2016 13:46","datam":"31\/05\/2017 20:06","timestampc":1460047579,"timestampm":1496272006}, ... etc. there is also other lists as subdirectories.
But in this particular server, I am getting this:
{"erro":"OK","Lista":{"22":{"nome":"a-process.gif","base":"a-process","ext":"gif","bytes":93117,"datac":"03\/08\/2016 18:33","datam":"03\/08\/2016 18:26","timestampc":1470249183,"timestampm":1470248785},"43":{"nome":"g-agenda.gif","base":"g-agenda","ext":"gif","bytes":1454,"datac":"03\/08\/2016 18:33","datam":"03\/08\/2016 18:26","timestampc":1470249183,"timestampm":1470248786}, ... etc.
Instead of "Lista" be rendered with "[", there is a "{". My testing server is running php 5.6.10 and this server is 5.6.27. I don't think is a version problem (really?) but maybe some directive is telling to work like this.
The simple solution is to convert those objects to array, no big deal, but I am trying to understand why this is happening and to optimize my code.
You need to start your array at 0 and increment contiguously to get a JSON array. Failing that, use array_values() to re-index the PHP array before json_encode().
In your first example the array index starts at 0 so json_encode() treats it as an array. In the second the array index starts at 22 so it is treated as an object. The indexes also need to be contiguous to generate an array. Somehow you generate or get different indexes in each instance (maybe sorting or other function that defines or moves the indexes).
This shows contiguous indexes starting at 0:
$v = range(1,5);
print_r($v);
echo json_encode($v);
Yields an array:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
[1,2,3,4,5]
While starting at 1:
$k = range(1,5);
$z = array_combine($k, $v);
print_r($z);
echo json_encode($z);
Yields an object:
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
{"1":1,"2":2,"3":3,"4":4,"5":5}
Starting at 0 with non-contiguous indexes:
$z = array(0, 2=>2, 3=>3, 5=>5);
print_r($z);
echo json_encode($z);
Yields an object:
Array
(
[0] => 0
[2] => 2
[3] => 3
[5] => 5
)
{"0":0,"2":2,"3":3,"5":5}

weird behavior of json_encode function

I have this normal array name $arr..
and trying to push something on the array using array_push() function.. like array_push( $arr['alerts_data'], 999 );
It produces this output:
Array
(
[alerts_data] => Array
(
[0] => 169
[1] => 175
[2] => 111
[3] => 48
[4] => 999
)
)
When i use json_encode I got:
{"alerts_data":[169,175,111,48,111,999]}
BUT, when I try to unset() something from $arr like:
unset( $arr['alerts_data'][4] );// will remove removes the 999
and then use the json_encode again, I got this json object
{"alerts_data":{"0":169,"1":175,"2":111,"3":48}}
What's wrong in here? can you tell? I want to achieve the first encoded json above by using the unset() function.
Yes, it's because the array keys aren't consecutive anymore, so it's treated as an associative array, and PHP associative arrays become JavaScript objects, because JavaScript does not have associative arrays.
Use array_splice() to cleanly remove elements from the array.
You have a gap in your keys (it goes from 3 to 5), so an object must be created for it to be valid. Two possible solutions:
array_splice($arr['alerts_data'], 4, 1);
unset($arr['alerts_data'][4]);
$arr['alerts_data'] = array_values($arr['alerts_data']);

Store an array to an array key

I'm trying to store an array ($temp) into the $data array, where key is prices.
$data['prices'] = $temp;
However, PHP converts the array into string instead and is throwing me and error.
Notice: Array to string conversion
Is $data = array('prices' => $temp); the only solution?
edit:
I found my mistake. Yes, $data was used previously as a string that's why PHP is converting the input into string.
Problem 2, doing a print_r on $data['prices'] = $xml->result->Prices->Price, shows only 1 set of array. But I am able to retrive 2 sets of result by doing a foreach loop on $data['prices']. Why is that so?
Content of $temp http://pastebin.com/ZrmnKUPB
Let me be more clear..
The full xml object I'm trying to extract information from: http://pastebin.com/AuMJiyrw
I'm only interested in the price array (Price_strCode and Price_strDescription) and store them in $data['prices']. End result something like this:
Array(
[0] => (
[Price_strCode] => 0001
[Price_strDescription] => Gold
)
[1] => (
[Price_strCode] => 0002
[Price_strDescription] => Silver
)
)
Unless you are doing some other array to string conversion elsewhere, the array is actually being stored as another array.
$data['prices'] will be an array, which can be accessed as $data['prices']['key'].
This is not possible, I have been doing this always and it works fine. You must be doing something else somewhere which is causing your array to convert to strong. share your code here

PHP variable to array

i need to convert a PHP $var to a array.
i did like this
$array = array();
$var=$array;
but this way the dosent give the output as this
Array ( [0] => [1] => 9 [2] => 7 [3] => 11 [4] => 5 )
its gives like
a normal varible print 154515100
It depends on what the variable is. If it is a string, do:
$array = str_split($var);
What is the variable to begin with?
If it was an object, you could cast it to an array like
$var=(array)$var;
It sounds like you want to convert from a string or an integer to an array, though. Please provide more details.
You should define $var as array first

Categories