Home > Software engineering >  How can i use some of the json elements in json array (not all of elements)
How can i use some of the json elements in json array (not all of elements)

Time:06-16

i want to create dynamic json array.

i am using this array :

$d = array(
        'key1' => 9,
        'key2' => 10,
        'key3' => 20,
        'key4' => 60,
        'key5' => 50,
        );

and i can decode this json and using it in my project.

But now i have to take some of them in this array. For example i have to use key3 and key5 and rebuild my json array.

CodePudding user response:

You can use array_intersect_key:

<?php


$d = array(
    'key1' => 9,
    'key2' => 10,
    'key3' => 20,
    'key4' => 60,
    'key5' => 50,
);


print_r(array_intersect_key($d, ['key3'=>'','key5'=>'']));

Result:

Array
(
    [key3] => 20
    [key5] => 50
)

If you want to get fancy, you could also add in array_flip:

<?php


$d = array(
    'key1' => 9,
    'key2' => 10,
    'key3' => 20,
    'key4' => 60,
    'key5' => 50,
);

$desiredKeys = ['key3','key5'];

$result = array_intersect_key($d, array_flip($desiredKeys));
print_r($result);
  • Related