duanke1286 2012-04-20 12:41
浏览 89
已采纳

从数组PHP生成逗号分隔的字符串列表

I am trying to write a function in PHP, but being a novice I am finding it a bit difficult to do so. I have an array which looks like

[{"x":"12345","y":"john"},{"x":"12345","y":"stars"}]

The function which I am writing is

function getCSV($x)
{

    // Now I want to pass the $x which in the above array is 12345 and get "john,stars"  as output
}

Are there any methods available in PHP that can do this, or what would be the best approach to get it?

  • 写回答

1条回答 默认 最新

  • donglan8999 2012-04-20 12:50
    关注

    That looks like a json to me

    [{"x":"12345","y":"john"},{"uid1":"12345","uid2":"stars"}]
    
    
    function getCSV($x)
    {
        $arr = json_decode($x);
        echo $arr[0]->y . ', ' . $arr[1]->uid2;
    }
    

    This looks horrible, but withouth further explanation is the only thing that works

    EDIT - after your edit

    function getCSV($x)
    {
        $arr = json_decode($x);
        $y = array();
        foreach($arr as $obj){
            $y[] = $obj->y;
        }
        return implode(',', $y);
    }
    

    here is a working pad http://codepad.org/HzttdmjW

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 安装 opencv4nodejs 报错
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!