将数组项合并为字符串

12

如何将数组中的所有元素合并成一个字符串?


1
你想让数组项用逗号分隔吗?如果是这样,你可以使用 $finalarr = array_merge($arr1, $arr2) 然后使用 implode(",", $finalarr)。希望这能帮到你。 - bharath
请查看implode - mschneider
我使用了array_merge,因为我误解了你的问题...当你说合并所有数组时。但是implode肯定是你的答案。 - bharath
10个回答

44

使用implode函数

例如:

$fruits = array('apples', 'pears', 'bananas');
echo implode(',', $fruits);

7

从 PHP 手册中尝试使用以下代码 (implode):

<?php
    $array = array('lastname', 'email', 'phone');
    $comma_separated = implode(",", $array);

    echo $comma_separated; // lastname, email, and phone

    // Empty string when using an empty array:
    var_dump(implode('hello', array())); // string(0) ""
?>

5
如果您只是想将数组中的所有字符串连接起来,那么您应该查看implode()

4
$array1 = array(
    "one",
    "two",
)
$array2 = array(
    "three",
    "four",
)
$finalarr = array_merge($array1, $array2);
$finalarr = implode(",", $finalarr);

将会产生这样的结果:一,二,三,四。


3
您可以使用join函数。它是implode的别名,并且在我看来更易读:
$fruits = array('apples', 'pears', 'bananas');
echo join(',', $fruits);

2
join 可能更易读,但 implode 绝对更令人兴奋。 - Buttle Butkus

1
join(" -- ", Array("a", "b")) == "a -- b"

实际上,join是implode函数的别名。


1
如果您想将一组对象的字符串表示合并为单个字符串,可以在这些对象的数组上使用implode。这些对象的类只需要定义了__toString()魔术方法即可。
class myClass {

  protected $name;
  protected $value;
  public function __construct($name,$value) {
    $this->name = $name;
    $this->value = $value;
  }

  public function __toString() {
    return $this->name . '/' . $this->value;
  }
}

$obj1 = new myClass('one',1);
$obj2 = new myClass('two',2);

$obj_array = array($obj1, $obj2);

$string_of_all_objects = implode('|',$obj_array);

echo $string_of_all_objects; // 'one/1|two/2'

我发现这个技巧对于快速获取一组对象的字符串表示在网页上显示很有用。无需使用 foreach 循环遍历对象数组,也不需要使用 echo $obj->get('name')
编辑:下面是一个使用 "collection" 类的示例。最后有两个输出(回显)。第二个应该是有效的,但我不确定第一个是否有效。
class myCollectionClass implements IteratorAggregate {
  protected $objects = array();

  public function __construct() {};
  public function add(myClass $object) {
    $this->objects[] = $object;
    return $this; // fluid
  }
  public function getIterator() { // for the interface
    return new ArrayIterator($this->objects);
  }
  public function __toString() {
    return implode($this->objects);
  }
}
$my_collection = new myCollectionClass();
$my_collection->add($obj1)->add($obj2); // add both myClass objects to the collection. can do in one line because fluid

//echo implode('|',$my_collection); // Comment out myCollectionClass's __toString method to test this. does it work? I'm not sure. But the next line will work thanks to myCollectionClass' __toString, which itself uses myClass's __toString

echo $my_collection; // same output as previous block before EDIT.

0

对于多维数组,例如:

 $multi_arrays = array(
            0 => array('model' => 'Product 1'),
            1 => array('model' => 'Product 2'),
            2 => array('model' => 'Product 3'),
            3 => array('model' => 'Product 4'));

 $pattern = array('/\[/', '/\]/', '/{"model":/', '/}/', '/\"/');

 $str_models = preg_replace($pattern, '', json_encode( $multi_arrays));

结果将会是:

产品1,产品2,产品3,产品4

您可以更改模式以获得任何想要的结果!


0
foreach($array as $key => $value) {

$string .= $value .' ';

}

为什么程序运行缓慢?“string”是什么意思?生成的字符串末尾为什么会有额外空格? - Kamil Szot
@cocacola09 - 尽可能使用内置函数,为什么要重复造轮子呢?保持代码简短;-) - Elitmiar
1
我完全承认implode是更好的解决方案,但他的回应是它很慢,这是完全错误的。所以我正在纠正他。我完全承认implode对于代码组织来说更好。 - cocacola09
1
+1 这个答案以一种良好的方式完成了问题所要求的一切。更优化的方法的巧合并不意味着这个答案没有帮助。 - Andomar
实际上,这并没有完成问题所要求的内容。正如Kamil Szot所提到的,最后一个值末尾有一个额外的空格。您必须随后执行trim($string)才能获得相同的结果。一点也不好。 - Buttle Butkus
显示剩余2条评论

0
$array= array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$string="";

foreach ( $tempas $array) {
  $string=$string.",".$temp;
}

+1 这个回答以良好的方式完成了问题所要求的一切。有更优化的方法这个巧合并不意味着这个答案没有帮助。 - Andomar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接