1

my MySQL query output is

dbcol_a | dbcol_b
dataA1 | dataB1
dataA1 | dataB2
dataA2 | dataB3
dataA2 | dataB4
dataA2 | dataB5

I wanna parse into struturized array like this:

arcol_a | arcol_b
dataA1 | dataB1
----------| dataB2
dataA2 | dataB3
----------| dataB4
----------| dataB5

thanks

3 Answers 3

3

This should do it:

$desired_array = array();
foreach ($query_output as $value)
{
  $desired_array[$value['arcol_a']][] = $value['arcol_b'];
}

This way you add each value in the second column to an array with an index of the first column.

Sign up to request clarification or add additional context in comments.

Comments

1
  1. Make an hashtable called arcol_a_array.
  2. Loop through your data. For each row, check and see if the current arcol_a value is a key in the arcol_a_array array. If not, add it. The value of this key should be an array with one element - the value of the current row's arcol_b
  3. If the arcol_a value existed in the arcol_a_array hashtable, modify the array to add the new value from arcol_b.

Comments

1
$arr = array();

while($row = mysql_fetch_assoc($result)) {
   if(isset($arr[$row['arcol_a']])) {
    $arr[$row['arcol_a']][] = $row['arcol_b'];
  } else {
    $arr[$row['arcol_a']] = array($row['arcol_b']);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.