Ibrahim Hafiji Ibrahim Hafiji - 1 year ago 72
MySQL Question

Add SQL query rows to a new array using PHP

I am executing a sql query on a database which returns all the data.

SQL Code

$sql_query3 = $DFS->prepare( "

select
*
from
TABLE_NAME
where

WHAT_I_WANT = '".$variable."'

" );

$sql_query3->execute();

$result3 = $sql_query3->fetchall();

print_r($result3);


Result of print_r($result3)

Array
(
[0] => Array
(
[REFERENCE] => GBBRF707321224
[WEIGHT] => 199.00
[VOLUME] => 0.398
)
)

Array
(
[0] => Array
(
[REFERENCE] => GBBRF707321222
[WEIGHT] => 620.00
[VOLUME] => 1.240
)
)

Array
(
[0] => Array
(
[REFERENCE] => GBBRF707321220
[WEIGHT] => 2465.00
[VOLUME] =>4.930
)
)


Result of print_r($new_array)

Array
(
[0] => GBBRF707321224
[1] => 199.00
[2] => 0.398
)
Array
(
[0] => GBBRF707321222
[1] => 620.00
[2] => 1.240
)
Array
(
[0] => GBBRF707321220
[1] => 2465.00
[2] => 4.930
)


I am then looping through $result3 and selecting the values that I want from them. After I have got all the information that I want, I want to add them into a new array. However, when I try to do that, it adds everything into one long array.

I then tried
$new_array = array();
and then
$new_array[] = $row3['One']
. This works but creates separate arrays each time it loops through.

I want to be able to keep the array that is being printed out, but how the $result3 array is formatted.

This is what Im doing right now

$new_array = array();

foreach( $result3 as $row3 ) {



$new_array[] = $row3[ 'REFERENCE' ];
$new_array[] = $row3[ 'WEIGHT' ];
$new_array[] = $row3[ 'VOLUME' ];



}


There are 2 issues with the $new_array.

First issue is that the rows are added to the $new_array with keys as index. I want to be able to insert a string as the key.

The second thing is that, I want the array to look like the $result3 array.

Like this

Array
(
[0] => Array
(

)
)


Any tips or ideas would be appreciated.

Answer Source

Because you are always creating new index for new_array. Try this:

$new_array = array();

foreach( $result3 as $row3 ) {

  $tmp_array = array();

  $tmp_array[]   = $row3[   'REFERENCE'              ];
  $tmp_array[]   = $row3[   'WEIGHT'                 ];
  $tmp_array[]   = $row3[   'VOLUME'                 ];
  $new_array[]   = $tmp_array;



}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download