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

将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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色