Reputation: 11
i want key_value from json data but don't use loop
$y = "2018";
$json = '[
{"2017":[{"p":"50","v":"55"}]},
{"2018":[{"p":"50","v":"55"}]}
]';
$obj = json_decode($json, true);
if(array_key_exists($y, $obj)){
return $json[$y];
} else {
return array_search($y, $obj);
}
return only number 1
Upvotes: 0
Views: 179
Reputation: 26
$num = array_walk($json, function($a) use ($i) {
$y = "2018";
if(isset($a[$y])){
return $i;
}
$i++;
});
return 1
Upvotes: 0
Reputation: 1584
ok so I have tried to complete it without using a loop, this may be what you are wanting or maybe not.
$y = "2018";
$json = '[
{"2017":[{"p":"50","v":"55"}]},
{"2018":[{"p":"50","v":"55"}]}
]';
$obj = json_decode($json, true);
function exists( $key, $value, $y )
{
global $result;
if( isset( $key[ $y ] ) )
{
$result = $key[ $y ];
}
}
array_walk( $obj, "exists", $y );
var_dump( $result );
Result:
array(1) {
[0]=>
array(2) {
["p"]=>
string(2) "50"
["v"]=>
string(2) "55"
}
}
Upvotes: 0
Reputation: 3658
I guess this is your expected answer
$y = "2018";
$json = '[
{"2017":[{"p":"50","v":"55"}]},
{"2018":[{"p":"50","v":"55"}]}
]';
$obj = json_decode($json, true);
return array_column($obj,$y);
This will return an array like below:
Array
(
[0] => Array
(
[0] => Array
(
[p] => 50
[v] => 55
)
)
)
Upvotes: 1
Reputation: 865
Since your json string is as follows when decoded:
Array
(
[0] => Array
(
[2017] => Array
(
[0] => Array
(
[p] => 50
[v] => 55
)
)
)
[1] => Array
(
[2018] => Array
(
[0] => Array
(
[p] => 50
[v] => 55
)
)
)
)
array_key_exists
looks whether the given key exists within the given array.
array_search
looks whether the given value occurs within the given array.
Those functions are not able to look into a multidimensional array. You should loop over the array and then execute your array_key_exists
and/or array_search
functions.
Upvotes: 0