0

I have a function that return array values as JSON object:

function keywords(){

    $keywords = array ('29254' => array('JOIN', 'PIN', 'WITHDRWAL', 'BALANCE'),
                        '24254' => array('UPNIN', 'PEIN', 'BALANCE'),
                      );

    return json_encode($keywords);
 }

print_r(keywords());

The result:

{"29754":["JOIN","PIN","WITHDRWAL","BALANCE"],"24254":["UPNIN","PEIN","BALANCE"]}

I want to get the array with the key 29254 only.

I tried this:

$data = json_decode(keywords());

print_r($data)[29254];

...but I still get all of them.

2

3 Answers 3

2

Hope this helps

$data = json_decode(keywords(), true);

print_r($data['29254']);

or try this

$data = json_decode(keywords());
print_r($data->{29254});

json_decode will return values inside the object.

Sign up to request clarification or add additional context in comments.

Comments

0

you can use this one:

   return json_encode($keywords[29254]);

output: ["JOIN","PIN","WITHDRWAL","BALANCE"]

Comments

0
function keywords($data=''){

    $keywords = array ('29254' => array('JOIN', 'PIN', 'WITHDRWAL', 'BALANCE'),
                        '24254' => array('UPNIN', 'PEIN', 'BALANCE'),
                      );

    return !empty($data) ? json_encode($keywords[$data]) : json_encode($keywords);
 }

print_r(keywords(29254));

2 Comments

why adding a default value to $data as this will throw a notice ?
Thank you @AymDev, I haven't noticed, i have updated the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.