-1

I have an object array which has key values

Array ( [0] =>stdClass Object ( [privacy] => {"name": "on", "email": null, "mobile": null, "address": "on", "alt_contact": "on"} ) )

I need to print a string which will contain the comma separated keys which has values as 'on'. The resultant string should be

$result = "name,address,alt_contact"; 

Please help

1

3 Answers 3

0

This would do the trick for you ..

$json = '{"name": "on", "email": null, "mobile": null, "address": "on", "alt_contact": "on"}';
$array = json_decode($json,true);

$str = "";
foreach($array as $key=>$value)
{
    if($value == "on")
        $str .= $key.",";
}
return rtrim($str,",");

result:- name,address,alt_contact

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

Comments

0

This is how your request translates to PHP:

I need to

This is the code, straight from the list above:

$json = '{"name": "on", "email": null, "mobile": null, "address": "on", "alt_contact": "on"}';
// Pass TRUE as second argument to get arrays back; stdObject is useless
$data = json_decode($json, TRUE);

// print comma separated keys of 'on'
echo(implode(',', array_keys($data, 'on')));

Comments

0

Thanks Jaimin, It helped

Had to get the $privacy object parsed in an array as

$userPrivacies = $userPrivacies[0]->privacy;

and used your code later.

so the solution becomes

$userPrivacies = $userPrivacies[0]->privacy;

$array = json_decode($userPrivacies,true);

$str = "";
foreach($array as $key=>$value)
{
   if($value == "on")
      $str .= $key.",";
}
echo rtrim($str,",");

1 Comment

if my answer worked for you, you should select my answer as accepted.. it is a way of appreciation on stackoverflow...

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.