Home > other >  Combine multiple arrays of same variable in a single array
Combine multiple arrays of same variable in a single array

Time:01-15

This is my code.

$users = array(83);

foreach($users as $user)
{
    $queryselectuser =  mysqli_query($connect,"SOME QUERY");
    while($rec_file=mysqli_fetch_array($queryselectuser)) 
    {
       $l['request_id']= $rec_file['request_id'];
       $l['fixer_id']= $rec_file['fixer_id'];
       print_r($l);
    }
}

And this is the result I am getting.

Array ( [request_id] => 1502 [fixer_id] => 84 )

Array ( [request_id] => 1500 [fixer_id] => 84 )

Array ( [request_id] => 1489 [fixer_id] => 84 )

But my expected o/p is :

Array (

Array ( [request_id] => 1502 [fixer_id] => 84 ),

Array ( [request_id] => 1500 [fixer_id] => 84 ),

Array ( [request_id] => 1489 [fixer_id] => 84 )

)

What I had Tried.

  • imploding arrays.
  • merging arrays.
  • combining arrays.

But nothing worked.

CodePudding user response:

If I understood you correctly, then maybe those examples can help you.

Example #1:

$users = array(83);
$dataUsers = [];

foreach($users as $user)
{
    $queryselectuser = mysqli_query($connect,"SOME QUERY");
    $itemCollection = [];
    while($recFile=mysqli_fetch_array($queryselectuser)) 
    {
       $item = [];
       $item['request_id'] = $recFile['request_id'];
       $item['fixer_id'] = $recFile['fixer_id'];
       $itemCollection[] = item;
    }
    $dataUsers[] = $itemCollection;
}

Example #2 (by using mysqli_fetch_all):

$users = array(83);
$dataUsers = [];
foreach($users as $user)
{
    $queryselectuser = mysqli_query($connect,"SOME QUERY");
    $dataUsers[] = mysqli_fetch_all($queryselectuser, MYSQLI_ASSOC);
}

CodePudding user response:

A few notes about the code:

  • You get that result of only just the arrays, as you are directly printing print_r($l); in the loop
  • If you want a collection of arrays, you can create an array $items for example, and on each iteration create a new array adding the values for request_id and fixer_id to it. Then use the userid as the key to be able to correlate the data afterwards if necessary
  • In the example code you are not using the value of $user from the foreach loop. It may be obvious, but the get the data related to that user, you have to use that value in your query

For example using your example code:

$users = array(83, 84);
$items = [];

foreach($users as $user)
{
    $queryselectuser =  mysqli_query($connect,"SOME QUERY");
    while($rec_file = mysqli_fetch_array($queryselectuser))
    {           
        $l['request_id']= $rec_file['request_id'];
        $l['fixer_id']= $rec_file['fixer_id'];
        $items[$user] = $l;
    }
}
print_r($items);

Example output

Array
(
    [83] => Array
        (
            [request_id] => request_id_1
            [fixer_id] => fixer_id_1
        )

    [84] => Array
        (
            [request_id] => request_id_2
            [fixer_id] => fixer_id_2
        )

)
  •  Tags:  
  • Related