将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 ) 
)
douxiyi2418
douxiyi2418 您不需要编写自己的array_combine()函数,它是内置于PHP中的。
一年多之前 回复
dsfgds4215
dsfgds4215 什么意味着列而不是行...?@Strawberry先生
一年多之前 回复
duanchuan6350
duanchuan6350 如果我使用$keys=Array('KD.1','KD.2','KD.3','KD.4','KD.5','KD.1','KD.2','KD.3','KD.4','KD.5');和$values=Array(0,0,1,1,0,0,1,1,1,0);我得到了我想要的东西。
一年多之前 回复
douba6365
douba6365 我希望你的意思是'专栏',而不是'排'!:-(
一年多之前 回复
doumi6685
doumi6685 var_dump($values)=“0,0,1,1,0,0,1,1,1,0”
一年多之前 回复
duanji5116
duanji5116 var_dump($keys)=“'KD.1','KD.2','KD.3','KD.4','KD.5','KD.1','KD.2','KD.3','KD.4','KD.5'”
一年多之前 回复
drgdn82648
drgdn82648 感谢您的评论,我用这个简单的方式..
一年多之前 回复
dtr53557
dtr53557 你可以var_dump一行并显示一个例子的输出,这样我们就可以确定表中的内容了吗?你能否展示一下你目前得到的输出的例子,而不是你想要得到的?(抱歉,一开始就落后了)
一年多之前 回复
dtjzpg5313
dtjzpg5313 你在哪里拿Array([0]=>0[1]=>0)等?我看到的是非常糟糕的SQL表架构
一年多之前 回复

1个回答

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);
  }
doubiaode0460
doubiaode0460 好主意,没想到那条捷径。
一年多之前 回复
douyi4912
douyi4912 他可以使用str_getcsv来解析CSV字符串 - 它将删除所有引号,分隔符并一次创建一个数组。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐