duanping1632
2016-10-19 20:02
浏览 8
已采纳

内置具有不同分隔符的多维数组?

I'm looking to implode my array into a string that looks like this:

1,a,v,v|2,b,v,v|3,c,v,v|4,d,v,v|5,d,v,v

Here's my array:

array (size=5)
  0 => 
    array (size=4)
      0 => string '1' (length=1)
      1 => string 'a' (length=1)
      2 => string 'v' (length=1)
      3 => string 'v' (length=1)
  1 => 
    array (size=4)
      0 => string '2' (length=1)
      1 => string 'b' (length=1)
      2 => string 'v' (length=1)
      3 => string 'v' (length=1)
  2 => 
    array (size=4)
      0 => string '3' (length=1)
      1 => string 'c' (length=1)
      2 => string 'v' (length=1)
      3 => string 'v' (length=1)
  3 => 
    array (size=4)
      0 => string '4' (length=1)
      1 => string 'd' (length=1)
      2 => string 'v' (length=1)
      3 => string 'v' (length=1)
  4 => 
    array (size=4)
      0 => string '5' (length=1)
      1 => string 'd' (length=1)
      2 => string 'v' (length=1)
      3 => string 'v' (length=1)

Any help would be greatly appreciated.

Thanks.

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

1条回答 默认 最新

  • douhao8456 2016-10-19 20:29
    已采纳

    If you were starting with an array of strings, like this:

    $strings = ['1,a,v,v', '2,b,v,v', '3,c,v,v', '4,d,v,v', '5,d,v,v'];
    

    It would be easy:

    $result = implode('|', $strings);
    

    You probably already know how to do that. So the question is how to get this array of arrays

    $arrays = [
        ['1','a','v','v'],
        ['2','b','v','v'],
        ['3','c','v','v'],
        ['4','d','v','v'],
        ['5','d','v','v']
    ];
    

    into the same format as $strings.

    Fortunately that's easy too. Just do the same thing, only in a loop.

    foreach ($arrays as $array) {
        // implode each item and add the result to a new array
        $strings[] = implode(',', $array);
    }
    

    It can also be done using the array_map function.

    $strings = array_map(function($array) {
        return implode(',', $array);
    }, $arrays);
    

    For something basic like this, it really doesn't matter which way you do it.

    打赏 评论

相关推荐 更多相似问题