重新创建可读数组

时间:2014-02-06 16:46:00

标签: php arrays

我的数组看起来像这样:CSV:

Array
(
    [0] => Array
        (
            [0] => Agent Name
            [1] => Total Calls
            [2] => Customer Services 
            [3] => Voicemail 
        )

    [1] => Array
        (
            [0] => Paul
            [1] => 53
            [2] => 0
            [3] => 0
        )

    [2] => Array
        (
            [0] => Sarah
            [1] => 51
            [2] => 0
            [3] => 0
        )
)

我想整理一个数组,使其更具可读性和易用性。

我希望数组看起来像这样:

Array
(
    [Paul] => Array
        (
            [Agent Name] => Paul
            [Total Calls] => 53
            [Customer Services ] => 30
            [Voicemail ] => 0
        )

    [Sarah] => Array
        (
            [Agent Name] => Sarah
            [Total Calls] => 51
            [Customer Services ] => 0
            [Voicemail ] => 0
        )

)

我想出了这个解决方案并且有效:

$fields = $report[0];
array_shift($report);

$data = array();

foreach($report as $row) {
      $data[$row[0]] = array();
      foreach($row as $k => $val) {
        $data[$row[0]][$fields[$k]] = $val;
      }
}

return $data;

这样做有更好的缩短方式吗?

2 个答案:

答案 0 :(得分:0)

尝试

$result =array();
for($i=1;$i<count($arr);$i++){
   $result[$arr[$i][0]] = array_combine(array_values($arr[0]),$arr[$i]);
 }

请参阅演示here

答案 1 :(得分:0)

你也许可以这样做:

$f = array_shift($report);

$a = array_combine(array_column($t = array_map(function ($r) use ($f)
{
  return array_combine($f, $r);
}
, $report), 'Agent Name'), $t);