deya tri
deya tri

Reputation: 53

convert sql query to array

I have try for days, to make my query row as array but haven't success yet. I have 'cat.1','cat.2','cat.3','cat.4','cat.5','cat.1','cat.2','cat.3','cat.4','cat.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['listcat']);
    $values = Array($row['rightval']);
    $final_array [$row['testid']]= 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 ( 
  [cat.1] => Array ( [0] => 0 [1] => 0 ) 
  [cat.2] => Array ( [0] => 0 [1] => 1 ) 
  [cat.3] => Array ( [0] => 1 [1] => 1 ) 
  [cat.4] => Array ( [0] => 1 [1] => 1 ) 
  [cat.5] => Array ( [0] => 0 [1] => 0 ) 
)
[8173] => Array ( 
  [cat.1] => Array ( [0] => 0 [1] => 0 ) 
  [cat.2] => Array ( [0] => 0 [1] => 1 ) 
  [cat.3] => Array ( [0] => 1 [1] => 1 )
  [cat.4] => Array ( [0] => 1 [1] => 1 ) 
  [cat.5] => Array ( [0] => 0 [1] => 0 ) 
)

Upvotes: 1

Views: 1362

Answers (1)

Barmar
Barmar

Reputation: 780869

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

Upvotes: 1

Related Questions