2

I have array:

$array = array(
   0 => array('first' => 'aaa',
              'second' => 'bbb'),
   1 => array('first' => 'erw',
              'second' => 'wer'),
   2 => array('first' => 'aaawe',
              'second' => '345'),
   3 => array('first' => 'aa345a',
              'second' => 'dfgdfg'),
);

and i would like get values with implode:

$first = implode(';', $array['first']);
$second = implode(';', $array['second']);

But of course this not working. How is the best way for this?

josh4356
  • 23
  • 2

2 Answers2

3

With PHP 5.5 there exists a function array_column(): http://php.net/array_column

$first = implode(';', array_column($array, 'first'));
// same for $second

P.s.: for backwards compability check also https://github.com/ramsey/array_column out


As requested, something "simple" (PHP 5.3 compatible):

$first = array_reduce($array, function ($array, $string) { return ($string !== null?"$string;":"").$array['first']; }, null);
bwoebi
  • 23,637
  • 5
  • 58
  • 79
1

you can do it without array_column();

<?php
 $array = array(
   0 => array('first' => 'aaa',
              'second' => 'bbb'),
   1 => array('first' => 'erw',
              'second' => 'wer'),
   2 => array('first' => 'aaawe',
              'second' => '345'),
   3 => array('first' => 'aa345a',
              'second' => 'dfgdfg'),
);
foreach ($array as $row)
{
  $values[] = $row['first'];
  $val[] = $row['second'];
}
$first= implode(',', $values);
$second= implode(',', $val);
echo $first."<br>";
echo $second;
?>

i tested and this gave me output

aaa,erw,aaawe,aa345a
bbb,wer,345,dfgdfg
Dinesh
  • 4,066
  • 5
  • 21
  • 35