lacyeex lacyeex - 6 months ago 31
PHP Question

PHP : Change Array structure

I've a set of array like this from selecting database, where [0] in the table is ID, [1] is Item, and [2] is Type :

Array
(
[0] => LO001
[1] => Fork
[2] => A
)
Array
(
[0] => LO002
[1] => Spoon
[2] => B
)


But i want it to be like this :

Array
(
[0] => Array
(
[0] => LO001
[1] => Fork
[2] => A
)
[1] => Array
(
[0] => LO002
[1] => Spoon
[2] => B
)
)


*edit, code for select data from DB, $selected is a set of an array from checkbox form result. :

$query = "SELECT ID, name, type FROM location WHERE loc_id = '$selected'";
$sqlcb = mysql_query($query);
$ccb = array();
while($ccb= mysql_fetch_array($sqlcb)) {
print_r($ccb);
}


$selected array structure example (this array could be change based on user input from checkbox form.

Array
(
[0] => LO001
[1] => LO002
)

Answer

Use something like:

while($ccb= mysql_fetch_array($sqlcb)) {
     $finalArray[] = $ccb;
}
print_r($finalArray);

Please note that mysql_* is now deprecated as of PHP7 because of security issues. It is suggested that you switch to mysqli_* or PDO extensions.

Comments