-2

我当前的 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 代码片段帮助我将一个数组转换为逗号分隔值。我将处理循环以将我的三个数组转换为字符串..

4

4 回答 4

3

如果您尝试将数组转换为逗号分隔的字符串,请使用 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
)

*/
于 2012-12-06T13:33:59.323 回答
2

这会做

$comma_separated = implode(",", $array);
于 2012-12-06T13:18:37.810 回答
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
于 2012-12-06T13:22:14.390 回答
1

不清楚你在问什么,但我假设你想要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"
}
**/
于 2012-12-06T13:25:16.627 回答