0

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

it worked prefectly. thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.