This question already has answers here:
Retrieving array keys from JSON input
(7 answers)
Closed 8 years ago.
I have created a simple json string to decode into a data array, but I am very confused about how to iterate through the array once it is decoded:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$data = json_decode($json, true);
for ($j = 0; $j < count($data); $j++) {
echo "$j: $data[$j]<br>";
}
?>
I can't seem to get this code to work because it is saying that every offset is undefined, so I think the trouble stems from my understanding of what an array looks like once it has been decoded.
When I do a var_dump(json_decode($json, true)), I get this result:
array (size=5)
'a' => int 1
'b' => int 2
'c' => int 3
'd' => int 4
'e' => int 5
So what does this mean exactly? Are the array indexes 'a', 'b', 'c', 'd', and 'e' respectively? If so, then how can I iterate through each of these to print out all of their values?
Arrays in PHP are not the same as arrays in JavaScript (or Json). However, what you're looking at here:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Is not actually a Json array, but a Json object. a, b, c, d, and e are properties of that object (which are a bit like indexes in a PHP array).
To iterate through the properties of this object, you can use a foreach loop:
$data = json_decode($json, true);
foreach ($data as $key => $value) {
echo "$key: $value<br>";
}
Related
This question already has answers here:
How to convert an array to object in PHP?
(35 answers)
PHP array_reduce with initial parameter as an array
(5 answers)
Closed 19 days ago.
This post was edited and submitted for review 19 days ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a simple php array that looks like this & I am looping over it to assign its keys as properties to an stdClass object & its values as the values of those keys. My code looks like this
$arr = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$obj = new stdClass();
foreach ($arr as $key => $value) {
$obj->{$key} = $value;
}
After this point, my $obj looks like this after a print in the popular laravel php repl, tinker. Its just convinient for me to work in there
{#4867
+"one": 1,
+"two": 2,
+"three": 3,
+"four": 4,
+"five": 5,
}
A regular var_dump would look like
object(stdClass)#4867 (5) {
["one"]=>
int(1)
["two"]=>
int(2)
["three"]=>
int(3)
["four"]=>
int(4)
["five"]=>
int(5)
}
but that's no biggie, my main question is why can't i set these properties in an array_reduce using array_keys to get the key & using the array above to grab the value of that key like so;
$arr = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$obj = new stdClass();
$result = array_reduce(
array_keys($arr),
function ($carry, $curr) use ($arr) {
return $carry->{$curr} = $arr[$curr];
},
$obj
);
Trying to run this piece of code throws the error
Error Attempt to assign property "two" on int.
Am pretty sure am missing something because just passing an array with one element works, ie reducing ['one' => 1] using the same method produces an stdClass object with one property, one with a value of 1
Your array_reduce callback returns this expression:
return $carry->{$curr} = $arr[$curr];
But that does not return the object -- it is just the value that was assigned to one object property.
You'll want the callback to always return the carry (accumulator).
So have the callback do the assignment and then return the object:
$carry->{$curr} = $arr[$curr];
return $carry;
This question already has answers here:
json with no index after unset encode array in php
(6 answers)
Closed 8 months ago.
I get a strange behavior when I remove data from my array with unset
$array = [['name' => "pepe"], ['name' => 'marta']];
unset($array[0]);
unset($array[1]);
And I append more objects to the array
$array[] = $value1;
$array[] = $value2;
echo json_encode($array);
When I convert $array into an object I get this key values insted of index values
{"2":{"name":"mario"},"3":{"name":"hector"}}
Expected output
[{"name":"mario"},{"name":"hector"}]
That's because php unset doesn't reduce the length of the array, it just empty the given key.
Since it doesn't change the length, whe. You do $array[] = something you continue incrementing the index, creating the 2 and 3 index you are seeing.
When you do json_encode, since the keys doesn't start from zero (or aren't contiguous), it need to represent this array as an object.
Exemplifying:
$var1 = [1 => 'a', 3 => 'b'];
Can only be serialized to
{"1": "a", "3": "b"}
Because you can't define the index of an array item using JSON.
Solution
You can still use unset(), but you need to get only array values using the array_values() function:
$array = [['name' => "pepe"], ['name' => 'marta']];
unset($array[0]);
unset($array[1]);
$array[] = $value1;
$array[] = $value2;
// $array is now [2=>$value1, 3=>$value2]
$array = array_values($array);
// $array is now [$value1, $value2]
echo json_encode($array);
// Now the json outputs as expected by you: ["value1", "value2"]
This question already has answers here:
Create an assoc array with equal keys and values from a regular array
(3 answers)
Closed 6 years ago.
I have this array:
$a = array('b', 'c', 'd');
Is there a simple method to convert the array to the following?
$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');
$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one element.
Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:
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.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 6 years ago.
Let's assume we have a simple $array like the following.
$array = array(
'a' => array(
'b' => array(
'c' => 'd'
),
'e' => 'f'
),
'g' => 'h'
);
Given an arbitrary array of $keys = array('a', 'b', 'c') and a value $value = 'i', I would like to change value of $array['a']['b']['c'] to i.
For simplicity, let's assume that elements of $keys are all valid, i.e. for any positive j, $keys[j] exists and is a child of $keys[j - 1].
I came up with a solution by passing a reference to the array and looping over keys but my implementation seems a bit ugly. Is there any straight forward way of doing this?
// current key index (starting at 0)
$i = 0;
// current array (starting with the outermost)
$t = &$array;
// continue until keys are exhausted
while ($i < count($keys) - 1) {
// update array pointer based on current key
$t = &$t[$keys[$i++]];
}
// update value at last key
$t[$keys[$i]] = $value;
http://sandbox.onlinephpfunctions.com/code/0598f00ab719c005a0560c18f91ab00154ba9453
This question already has answers here:
Help editing JSON to make an array rather than a 'dictionary'
(2 answers)
Closed 9 years ago.
I am having arrays from my PHP
{"lista":[{"Grad":"Beograd"},{"Grad":"Novi_Sad"},{"Grad":"Beograd"},{"Grad":"Novi_Sad"},{"Grad":"Beograd"},{"Grad":"Beograd"},{"Grad":"Beograd"},{"Grad":"Kragujevac"},{"Grad":"Kragujevac"},{"Grad":"Beograd"},{"Grad":"Kragujevac"},{"Grad":"Beograd"}]}
and when I use:
$arr = array_flip(array_map('serialize', $rows));
$lista = array_map('unserialize', array_flip($arr));
echo json_encode((object) array('lista' => $lista));
I am getting
{"lista":{"19":{"Grad":"Beograd"},"18":{"Grad":"Novi_Sad"},"20":{"Grad":"Kragujevac"}}}
Question is how can I remove this numbers that are in front of my arrays?
Try changing
echo json_encode((object) array('lista' => $lista));
to
echo json_encode((object) array('lista' => array_values($lista)));
Note : not tested
I think you need to populate the array as in the example in the documentation in the php manual:
http://php.net/manual/en/function.json-encode.php
From PHP Site:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
apply array_values before encoding into Json_encode
$lista = array_values(array_map('unserialize', array_flip($arr)));
echo json_encode((object) array('lista' => $lista));