dtny30176 2019-06-10 22:23
浏览 603
已采纳

将sql查询转换为数组

I have try for days, to make my query row as array but haven't success yet. I have 'KD.1','KD.2','KD.3','KD.4','KD.5','KD.1','KD.2','KD.3','KD.4','KD.5' in mysql row and want to make this as array so i will get 10 array rather than 1. Next i will use it to combine with another row that has same pattern. Look like this 0,0,1,1,0,0,1,1,1,0

while($row = $result->fetch_array(MYSQLI_ASSOC))  
  {  
    $keys = Array($row['listkd']);
    $values = Array($row['rightval']);
    $final_array [$row['testnis']]= array_combine_($keys, $values);
  }

my function array_combine_ i get from here

function array_combine_($keys, $values){
    $result = array();

    foreach ($keys as $i => $k) {
     $result[$k][] = $values[$i];
     }

    array_walk($result, function(&$v){
     $v = (count($v) == 1) ? array_pop($v): $v;
     });

    return $result;
}

I always get one array rather than ten, so its can't be combine two arrays. What i want the result is like this

[8131] => Array ( 
  [KD.1] => Array ( [0] => 0 [1] => 0 ) 
  [KD.2] => Array ( [0] => 0 [1] => 1 ) 
  [KD.3] => Array ( [0] => 1 [1] => 1 ) 
  [KD.4] => Array ( [0] => 1 [1] => 1 ) 
  [KD.5] => Array ( [0] => 0 [1] => 0 ) 
)
[8173] => Array ( 
  [KD.1] => Array ( [0] => 0 [1] => 0 ) 
  [KD.2] => Array ( [0] => 0 [1] => 1 ) 
  [KD.3] => Array ( [0] => 1 [1] => 1 )
  [KD.4] => Array ( [0] => 1 [1] => 1 ) 
  [KD.5] => Array ( [0] => 0 [1] => 0 ) 
)
  • 写回答

1条回答 默认 最新

  • drgm51600 2019-06-11 01:09
    关注

    Array($row['listkd']) will not parse the string as separate array elements. It just creates an array with a single element, which is the entire contents of the listkd column.

    You can use str_getcsv() to parse the string. It will split it on the commas, and parse the quotes as delimiters around the values.

    while($row = $result->fetch_array(MYSQLI_ASSOC))  
      {  
        $keys = str_getcsv($row['listkd'], ",", "'");
        $values = str_getcsv($row['rightval'], ",", "'");
    
        $final_array [$row['testnis']]= array_combine_($keys, $values);
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答