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

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

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题