【问题标题】:Parsing Array to string将数组解析为字符串
【发布时间】:2017-02-02 01:45:51
【问题描述】:

我有一个包含键值的对象数组

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

我需要打印一个字符串,其中包含逗号分隔的键,其值为“on”。结果字符串应该是

$result = "name,address,alt_contact"; 

请帮忙

【问题讨论】:

标签: php json


【解决方案1】:

这对你有用..

$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,",");

结果:- 姓名、地址、alt_contact

【讨论】:

    【解决方案2】:

    这是您的请求转换为 PHP 的方式:

    我需要

    这是代码,直接来自上面的列表:

    $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')));
    

    【讨论】:

      【解决方案3】:

      感谢 Jaimin,它有帮助

      必须将 $privacy 对象解析为数组

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

      并稍后使用您的代码。

      所以解决方案变成了

      $userPrivacies = $userPrivacies[0]->privacy;
      
      $array = json_decode($userPrivacies,true);
      
      $str = "";
      foreach($array as $key=>$value)
      {
         if($value == "on")
            $str .= $key.",";
      }
      echo rtrim($str,",");
      

      【讨论】:

      • 如果我的回答对你有用,你应该选择我的回答作为接受。这是对stackoverflow的一种欣赏方式......
      猜你喜欢
      • 1970-01-01
      • 2012-10-14
      • 2017-04-04
      • 2014-03-04
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多