在php中从现有数组创建新数组

时间:2014-04-04 07:44:51

标签: php arrays

美好的一天 我有一个包含以逗号分隔的数据的数组:

array (
       [0]=>Jack,140101d,10
       [1]=>Jack,140101a,15
       [2]=>Jack,140101n,20
       [3]=>Jane,141212d,20
       [4]=>Jane,141212a,25
       [5]=>Jane,141212n,30
      )

有很多数据,我希望将数据设置为:

array(
      [Jack]=>
          [140101]
              =>[d] =>10
              =>[a] =>15
              =>[n] =>20
      )

我的代码:

           foreach ($out as $datavalue) {
                    $dat = str_getcsv($datavalue,',');
                    $datevalue = substr($dat[1],2,-1);
                    $shiftvalue = substr($dat[1],-1);
                    $totalvalue = $dat[2];
                    $sval[$shiftvalue] = $totalvalue;
                    $dval[$datevalue] = $sval;
                    $opvalue = $dat[0];
                    $final[$opvalue] = $dval;
           }

现在看来,即使原始字符串中没有数据,也会填充数组,因此我的输出显示Jack在其他日期的结果,即使最初没有他的数据。希望这是有道理的。有人可以指出或建议一个解决方案吗?

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,explode就是您所需要的。请参阅this working here

<?php

$input = array (
  0 => 'Jack,140101d,10',
  1 => 'Jack,140101a,15',
  2 => 'Jack,140101n,20',
  3 => 'Jane,141212d,20',
  4 => 'Jane,141212a,25',
  5 => 'Jane,141212n,30',
);

$result = array();

foreach ($input as $key => $value) {
  $valueParts = explode(',',$value); // now valueparts is an array like ('Jack','140101d','10')
  $namePart     = $valueParts[0];
  $idPart   = substr($valueParts[1],0,-1); // we need to strip the letter from the id
  $charPart     = substr($valueParts[1],-1); // and the id from the letter
  $nrPart   = $valueParts[2]; // you could use intval() to make this an integer rather than a string if you want

  // Now we fill the array
  if(!array_key_exists($namePart, $result)) {
    $result[$namePart] = array();
  }
  if(!array_key_exists($idPart, $result[$namePart])) {
    $result[$namePart][$idPart] = array();
  }
  if(!array_key_exists($charPart, $result[$namePart][$idPart])) {
    $result[$namePart][$idPart][$charPart] = $nrPart;
  }
}

var_dump($result);