-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

  • Hope it's a duplicate question. check the answer using this link http://stackoverflow.com/questions/21168422/how-to-access-a-property-of-an-object-stdclass-object-member-element-of-an-arr – Sathiya saravana Babu Sep 24 '16 at 07:20

3 Answers3

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

Jaimin
  • 872
  • 6
  • 15
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')));
axiac
  • 68,258
  • 9
  • 99
  • 134
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,",");
  • if my answer worked for you, you should select my answer as accepted.. it is a way of appreciation on stackoverflow... – Jaimin Sep 27 '16 at 09:36