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?

5
  • Try to use implode function: $myGoal = implode(',', $myAssociativeA{'type'}); Commented Mar 23, 2015 at 19:38
  • 3
    What would be your expect output? (@bcesars join and implode is the same) Commented Mar 23, 2015 at 19:40
  • 1
    @bcesars, I have tried implode, it gave me an error Commented Mar 23, 2015 at 19:44
  • @Rizier123, I have updated my question with my hoped for output Commented Mar 23, 2015 at 19:44
  • @AmmarCSE see my answer below Commented Mar 23, 2015 at 19:57

5 Answers 5

17

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

I like your suggestion using array_column. Is there a version of the function 'array_column' compatible with PHP versions < 5.5?
@AmmarCSE You could use this implementation: 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
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+

Comments

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

8 Comments

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 Thanks, I will edit with your recommendation, but not all the answers have this and they are not downvoted.
@AdrianCidAlmaguer the two upvoted answers have that flexibility ;)
@scrowler see the Rizier123 answer, only works with the column "type"
Just to add this here, this answer isn't really that much backwards compatible it's only for: PHP 5 >=5.3!
|
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;
   }
?>

Comments

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.

2 Comments

Just thought I'd mention that there is a difference between CSV (a formatting standard) and comma delimited
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.