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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试用PHP编写一个函数,但作为一个新手,我觉得这样做有点困难 。 我有一个看起来像

  [{“x”:“12345”,“y”:“john”},{“x”:“12345”,“  y“:”stars“}] 
   
 
 

我写的函数是

  function getCSV($  x)
 {
 
 //现在我想传递上面数组中的$ x为12345并输出“john,stars”作为输出
} 
   
  
 

PHP中是否有可以执行此操作的方法,或者获取它的最佳方法是什么?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题