Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional Array PHP Implode

Tags:

In terms of my data structure, I have an array of communications, with each communications_id itself containing three pieces of information: id, score, and content.

I want to implode this array in order to get a comma separated list of ids, how do I do this?

like image 378
Spencer Avatar asked Mar 09 '11 17:03

Spencer


2 Answers

Update for PHP 5.5

PHP 5.5 introduces array_column which is a convenient shortcut to a whole class of array_map usage; it is also applicable here.

$ids = array_column($communications, 'id'); $output = implode(',', $ids); 

Original answer

You need to make an array of just ids out of your array of communications. Then the implode would be trivial.

Hint: the function for that is array_map.

Solution:

Assumes PHP 5.3, otherwise you 'd have to write the callback as a string.

$ids = array_map(function($item) { return $item['id']; }, $communications); $output = implode(',', $ids); 
like image 153
Jon Avatar answered Oct 21 '22 07:10

Jon


You can have a look to array_walk_recursive function . This is a working snippet of creating of recursive array to string conversion :

$array =    array(     "1"    => "PHP code tester Sandbox Online",       "foo"  => "bar",       5 ,       5     => 89009,      "case" => "Random Stuff",      "test" =>         array(          "test"  => "test221",          "test2" => "testitem"        ),     "PHP Version" => phpversion()   );  $string="";  $callback =    function ($value, $key) use (&$string) {      $string .= $key . " = " . $value . "\n";   };  array_walk_recursive($array, $callback);  echo $string; ## 1 = PHP code tester Sandbox Online ## foo = bar ## 2 = 5 ## 5 = 89009 ## case = Random Stuff ## test = test221 ## test2 = testitem ## PHP Version = 7.1.3 
like image 22
KB9 Avatar answered Oct 21 '22 06:10

KB9