22

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?

Spencer
  • 21,348
  • 34
  • 85
  • 121
  • 1
    Hi, could you post an example of the data sctructure and the resulting desired CSV? anyway i thing it can be done with implode and some loops. – SubniC Mar 09 '11 at 17:42

5 Answers5

60

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);
Jon
  • 428,835
  • 81
  • 738
  • 806
  • I am curious as to what $item represents? – Spencer Mar 09 '11 at 17:50
  • @Spencer: It represents "each one" of the items in `$communications`, as it is being passed to the callback function for mapping to something else. It's just the name of a formal parameter; you can use any other name just as well. – Jon Mar 09 '11 at 17:56
  • thank you so much! I have one last question. If only wanted to take the first 60 ids, how would you suggest I do that? – Spencer Mar 09 '11 at 18:04
  • 1
    @Spencer: `$firstN = array_slice($allOfThem, 0, $n);`. The PHP array functions are *extremely* useful and versatile. Spend some time to familiarize yourself with them: http://www.php.net/manual/en/ref.array.php. – Jon Mar 09 '11 at 18:09
4

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
petermeissner
  • 12,234
  • 5
  • 63
  • 63
KB9
  • 599
  • 2
  • 7
  • 16
3

From http://snipplr.com/view.php?codeview&id=10187:

class Format {
    static public function arr_to_csv_line($arr) {
        $line = array();
        foreach ($arr as $v) {
            $line[] = is_array($v) ? self::arr_to_csv_line($v) : '"' . str_replace('"', '""', $v) . '"';
        }
        return implode(",", $line);
    }

    static public function arr_to_csv($arr) {
        $lines = array();
        foreach ($arr as $v) {
            $lines[] = self::arr_to_csv_line($v);
        }
        return implode("\n", $lines);
    }

}
Nick
  • 1,311
  • 2
  • 10
  • 27
0

For anyone else looking for an answer, this is what I was able to do:

$singleDimensionalArray = array();

foreach($array["1"]["2"]["3"][...] as $value) {
    $singleDimensionalArray[] = $value;
}

I used this with a 3-dimensional array.

JonaK
  • 129
  • 1
  • 8
0

this comment based on @jon solution , just add functional code block

but i have to use loop because array_map does not accept second parameter

function array_column_implode($data_array = array(),$key = 'id', $delimiter = ',')
{
  if (function_exists('array_column'))
  {
    return implode($delimiter, array_column($data_array, $key));
  }
  else
  {
    $new_data_array = array();
    foreach ($data_array as $value) {
      if (isset($value[$key]))
      {
        $new_data_array[] = $value[$key];
      }
    }
    return implode($delimiter, $new_data_array);
  }
}
Bdwey
  • 1,813
  • 1
  • 16
  • 18