How do I merge all the array items into a single string?
If you are trying to just concatenate all of strings in the array, then you should look at implode().
Use the implode function.
For example:
$fruits = array('apples', 'pears', 'bananas');
echo implode(',', $fruits);
If you want to merge the string representation of a group of objects into a single string, you can use implode on an array of those objects. The objects' classes just have to have the __toString()
magic method defined.
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'
I found that trick useful to quickly get a string representation of a group of objects for display on a webpage. No need to loop through the object array with foreach
and using echo $obj->get('name')
.
EDIT: And here's and example with a "collection" class. I have 2 outputs (echos) at the end. The 2nd one should work, but I'm not sure about the 1st.
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.
For Multi Array such as:
$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));
The result will be:
Product 1, Product 2, Product 3, Product 4
You can change pattern for get any result you want!