简体   繁体   中英

how to get number key value from json php

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

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
                )

        )

)

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.

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"
 }
}
    $num = array_walk($json, function($a) use ($i) {
        $y = "2018";
        if(isset($a[$y])){
            return $i;
        }
        $i++;
    });

return 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM