3

Ok, I know that to get a comma-seperated string from a string array in PHP you could do

$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);

But what if I have an array of arrays(not a simple string array)?

$myAssociativeA = 
      array(
           [0] => array("type"=>"cat", "sex"=>"male")
           , [1] => array("type"=>"dog", "sex"=>"male")
      );

and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried

$myGoal = join(',', $myAssociativeA{'type'});

My target value for $myGoal in this case would be "cat,dog". Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53

5 Answers5

18

This should work for you:

(Here I just get the column which you want with array_column() and simply implode it with implode())

echo implode(",", array_column($myAssociativeA, "type"));
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • I like your suggestion using array_column. Is there a version of the function 'array_column' compatible with PHP versions < 5.5? – AmmarCSE Mar 23 '15 at 19:52
  • @AmmarCSE You could use this implementation: https://github.com/ramsey/array_column/blob/master/src/array_column.php Or do it with `array_map()`. But I think we live in 2015 so you should have at least php 5.5 – Rizier123 Mar 23 '15 at 19:54
2

Another option is to use array_walk() to return the key you want:

array_walk($myAssociativeA, function(&$value, $key, $return) {
  $value = $value[$return];
}, 'type');

echo implode(', ', $myAssociativeA); // cat, dog

Useful for older PHP versions - @Rizier123's answer using array_column() is great for PHP 5.5.0+

scrowler
  • 24,273
  • 9
  • 60
  • 92
2

You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to @Rizier123) and you can't use array_column()

<?php

$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));

$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));

echo $myGoal;
?>

EDIT: with the recommendation in the comment of @scrowler the code now is:

<?php

$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';

$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));

echo $myGoal;
?>

Output:

cat,dog

Read more about array_map in: http://php.net/manual/en/function.array-map.php

Community
  • 1
  • 1
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
  • heh, I dont know why people voted you down. It worked for me on PHP < 5.5 – AmmarCSE Mar 23 '15 at 20:03
  • @AmmarCSE they are crazy and sick! – Adrian Cid Almaguer Mar 23 '15 at 20:05
  • I'm not the downvoter, but I'd assume that it's because it gives no ability to have a dynamic column (type) since you've hard coded it into the callback – scrowler Mar 23 '15 at 20:10
  • @scrowler Thanks, I will edit with your recommendation, but not all the answers have this and they are not downvoted. – Adrian Cid Almaguer Mar 23 '15 at 20:16
  • @AdrianCidAlmaguer the two upvoted answers have that flexibility ;) – scrowler Mar 23 '15 at 20:20
  • @scrowler see the Rizier123 answer, only works with the column "type" – Adrian Cid Almaguer Mar 23 '15 at 20:22
  • Just to add this here, this answer isn't really that much backwards compatible it's only for: `PHP 5 >=5.3`! – Rizier123 Mar 23 '15 at 20:25
  • @AdrianCidAlmaguer Both. [Anonymous functions](http://php.net/manual/en/functions.anonymous.php) are introduced in PHP 5.3 so the gab to 5.5 isn't to big and also we live in 2015 so for what do we have `array_column()` to wait until 2020? – Rizier123 Mar 23 '15 at 20:31
  • @Rizier123 I agree with you, but I see many peoples in SO that don't have PHP 5.5.0, they will have their reasons – Adrian Cid Almaguer Mar 23 '15 at 20:33
  • @AdrianCidAlmaguer *but I see many peoples in SO that don't have PHP 5.5.0* Me too! I also saw many people in 2014 which didn't had PHP 5.5, but now we live in 2015 and PHP 7 is right before our doors! So why do we wait? We just can open the door and use it! – Rizier123 Mar 23 '15 at 20:36
0

You just have to loop over the array and generate the string yourself.

<?php
   $prepend = '';
   $out = '';
   $myAssociativeA = array(
      array('type' => 'cat'),
      array('type' => 'dog')
   );

   foreach($myAssociativeA as $item) {
      $out .= $prepend.$item['type'];
      $prepend = ', ';
   }
   echo $out;
?>

You could easily turn this into a function.

<?php
   function implode_child($array,$key) {
     $prepend = '';
     $out = '';
     foreach($array as $item) {
        $out .= $prepend.$item[$key];
        $prepend = ', ';
     }
     return $out;
   }
?>
David
  • 4,313
  • 1
  • 21
  • 29
0

Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.

$csvString = "";
foreach ( $myAssociativeA as $row ) {
    $csvRow = implode(",", $row);
    $csvString .= $csvRow . PHP_EOL;
}

Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.

NemanjaSRB
  • 398
  • 1
  • 16
  • Just thought I'd mention that there is a difference between CSV (a formatting standard) and comma delimited – scrowler Mar 23 '15 at 19:52
  • I agree - CSV standard contains additional details and not just the delimiter. From the question I've got under impression that he's problem is how to serialize assoc array so I focused on that issue. – NemanjaSRB Mar 23 '15 at 19:56