【问题标题】:2 dimenstional array into strings with comma saparated [closed]二维数组以逗号分隔的字符串[关闭]
【发布时间】:2012-11-24 12:41:13
【问题描述】:

我当前的 php 代码返回三个数组。我想将这三个数组转换为 3 个逗号分隔的字符串。

我的数组回显看起来像这样..

array (size=3)
     0 => 
    array (size=3)
      0 => string '1' (length=1)
      1 => string 'here' (length=4)
      2 => string 'Skincare composition against free radicals' (length=42)
  1 => 
    array (size=3)
      0 => string '2' (length=1)
      1 => string 'tere' (length=4)
      2 => string 'Compositions and methods for modification of skin lipid content' (length=63)
  2 => 
    array (size=3)
      0 => string '3' (length=1)
      1 => string 'fere' (length=4)
      2 => string 'Method and apparatus for acne treatment' (length=39) 

帮助我用一个简单的 php 代码 sn-p 将一个数组转换为逗号分隔的值。我将处理循环以将我的三个数组转换为字符串..

【问题讨论】:

  • @deceze 但是implode 更具戏剧性!
  • @Leigh 我宁愿所有字符串到join 和谐...! :3

标签: php arrays string type-conversion comma


【解决方案1】:

这样就可以了

$comma_separated = implode(",", $array);

【讨论】:

  • 你试过内爆多维数组吗?
  • @RobMasters 他已经指定他只需要转换一个数组的帮助,其余的他会处理
【解决方案2】:

将您的数组命名为for example: $array1,然后使用 foreach 创建一个数组。从那里使用 implode 制作一个字符串。例如:

foreach ($array1 as $value1){
 foreach ($value1 as $value){
  $newString[]=$value;
 }
}
$string=implode(", ", $newString);
echo $string; //will echo comma separated string

【讨论】:

  • 感谢这对我有用
【解决方案3】:

不清楚你在问什么,但我假设你想implode 内部数组并最终得到一个由 3 个字符串组成的数组。如果我是对的,以下方法可以解决问题:

$arr = array(
  array(1, 'badger', 'longer text about badger'), 
  array(2, 'ferret', 'longer text about ferret'), 
  array(3, 'hamster', 'longer text about hamster'), 
);

// This is the line you're interested in
$newArr = array_map(function($el) { return implode(', ', $el); }, $arr);

var_dump($newArr);

/** Gives output:
array(3) {
  [0]=>
  string(35) "1, badger, longer text about badger"
  [1]=>
  string(35) "2, ferret, longer text about ferret"
  [2]=>
  string(37) "3, hamster, longer text about hamster"
}
**/

【讨论】:

    【解决方案4】:

    如果您想将数组转换为逗号分隔的字符串,请使用 implode() :

    <?php
        $oldArray = array(array("red","green","blue"),array("Larry","Moe","Curly"),array("puppy dogs","rainbows","butterflies"));
    
        foreach($oldArray as $array){
            $newArray[] = implode(",",$array);
        }
    
        echo "<pre>";
        print_r($newArray);
        echo "</pre>";
    ?>
    
    /*
    Output:
    Array
    (
        [0] => red,green,blue
        [1] => Larry,Moe,Curly
        [2] => puppy dogs,rainbows,butterflies
    )
    
    */
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 2018-03-21
      • 2019-05-15
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多