在多阵列上内爆

时间:2013-10-06 15:28:03

标签: php arrays

我有阵列:

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

但当然这不起作用。最好的方法是什么?

2 个答案:

答案 0 :(得分:3)

使用PHP 5.5,存在一个函数array_column()http://php.net/array_column

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

P.s。:对于向后兼容性检查https://github.com/ramsey/array_column out


根据要求,“简单”(PHP 5.3兼容):

$first = array_reduce($array, function ($array, $string) { return ($string !== null?"$string;":"").$array['first']; }, null);

答案 1 :(得分: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