Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i use some of the json elements in json array (not all of elements)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading