Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Try to use implode function: $myGoal = implode(',', $myAssociativeA{'type'}); –  bcesars yesterday
3  
What would be your expect output? (@bcesars join and implode is the same) –  Rizier123 yesterday
    
@bcesars, I have tried implode, it gave me an error –  AmmarCSE yesterday
    
@Rizier123, I have updated my question with my hoped for output –  AmmarCSE yesterday
    
@AmmarCSE see my answer below –  Adrian Cid Almaguer yesterday

5 Answers 5

up vote -1 down vote accepted

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

share|improve this answer
    
why vote down? The code works –  Adrian Cid Almaguer yesterday
    
heh, I dont know why people voted you down. It worked for me on PHP < 5.5 –  AmmarCSE yesterday
    
@AmmarCSE they are crazy and sick! –  Adrian Cid Almaguer yesterday
    
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 yesterday
    
@scrowler Thanks, I will edit with your recommendation, but not all the answers have this and they are not downvoted. –  Adrian Cid Almaguer yesterday

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"));
share|improve this answer
    
I like your suggestion using array_column. Is there a version of the function 'array_column' compatible with PHP versions < 5.5? –  AmmarCSE yesterday
    
@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 –  Rizier123 yesterday

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+

share|improve this answer

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;
   }
?>
share|improve this answer

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.

share|improve this answer
    
Just thought I'd mention that there is a difference between CSV (a formatting standard) and comma delimited –  scrowler yesterday
    
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 yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.