duanhe4155 2014-04-04 07:44
浏览 20
已采纳

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

Good Day I have an array containing data seperated by a comma:

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
      )

There is a lot of data and I would like the data to be set out as:

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

My code:

           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;
           }

Now it seems the array is populated even if there is no data from the original string, so my output shows results for Jack on the other dates even though there was no data for him originally. Hope this makes sense. Could anyone point out or suggest a solution please?

  • 写回答

1条回答 默认 最新

  • duanduji2986 2014-04-04 07:56
    关注

    As mentioned in the comments, explode is what you need. See 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题