2

我有数组:

$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'),
);

我想通过内爆获得值:

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

但这当然行不通。最好的方法是什么?

4

2 回答 2

3

PHP 5.5 有一个函数array_column(): http: //php.net/array_column

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

Ps:对于向后兼容性检查也https://github.com/ramsey/array_column out


根据要求,一些“简单”的东西(PHP 5.3 兼容):

$first = array_reduce($array, function ($array, $string) { return ($string !== null?"$string;":"").$array['first']; }, null);
于 2013-10-06T15:29:47.580 回答
1

你可以做到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;
?>

我测试了,这给了我输出

aaa,erw,aaawe,aa345a
bbb,wer,345,dfgdfg
于 2013-10-06T16:09:53.613 回答