I am trying to get a certain value out of an array. Example of the array is:
array(2) {
["error"]=>
array(0) {
}
["result"]=>
array(1) {
["open"]=>
array(1) {
["12345-AAAAA-66AAKK"]=>
array(14) {
["inf"]=>
Usually when I want a certain value I would use:
$datawanted=$data[result][open][value];
However, in this case the first array is a variable that always changes (12345-AAAAA-66AAKK), I need to find the value of that.
I tried getting this with reset()
and key[0]
but this not give the wanted result.
Is there a way to get the output of the first element in the result array?
You can use array_search: http://php.net/manual/de/function.array-search.php
Example:
foreach ($array['result']['open'] as $dynamicKey => $item) {
if ($key = array_search('Value you are looking for', $item) {
$datawanted=$array['result']['open'][$dynamicKey][$key];
}
}
$data[result][open]
is not a correct way to access array items.
The token result
looks like a constant. PHP searches for a constant named result
, cannot find one and triggers a notice. Then it thinks "I guess the programmer wanted to write 'result'
(a string, not a constant). I'll convert it as string to them." and uses 'result'
instead.
It works but it's a horrible practice. It dates from the prehistory of PHP, 20 years ago and it's not recommended.
After you fix your code to correctly denote the keys of an array, the next step is to pick one of the many PHP ways to access values in the array.
You can get the first value of an array without knowing its key ($data['result']['open']['12345-AAAAA-66AAKK']
) by using the function reset()
:
$datawanted = reset($data['result']['open']);
Or you can use the function array_values()
to get only the values of the array (the keys are ignored, the returned array have the values indexed from zero) then your desired data is at position 0
on this array:
$values = array_values($data['result']['open']);
$datawanted = $values[0];
Another option, if you don't need to keep $data
for further processing, is to use the PHP function array_shift()
to remove the first value from the array and return it. Be warned that this function modifies the array it receives as argument:
$datawanted = array_shift($data['result']['open']);
If you need to process all the values of $data['result']['open']
(and you probably do) then the best way is to use the foreach
PHP statement. It allows you to access both the key and the value of each element of the array:
foreach ($data['result']['open'] as $key => $value) {
// $key is '12345-AAAAA-66AAKK'
$datawanted = $value;
}