amit
amit

Reputation: 1209

How to put value to blank array inside foreach loop php

I am using query in foreach loop (according to userType) and after query in foreach loop i am getting following result

Array
(
    [0] => Array
        (
            [bookingId] => 1
            [userId] => 102
            [status] => paid
        }
    [0] => Array
        (
            [bookingId] => 3
            [userId] => 102
            [status] => paid
        }       
    [0] => Array
        (
            [bookingId] => 5
            [userId] => 102
            [status] => paid
        }
...     
        
}           

Now i want all result outside foreach loop so i tried with following code but not working,showing me single record istead of multiple

I tried with following code but not working for me

$record=array();
    foreach ($result as $key => $row)
    {
            $query= // mysql query
            $rows = $query->result_array();
            $record['bookingId']=$rows['0']['bookingId'];
            $record['userId']=$rows['0']['userId'];
            $record['status']=$rows['0']['status'];
    }
echo "<pre>";print_R($record);

Upvotes: 2

Views: 448

Answers (2)

Amit Merchant
Amit Merchant

Reputation: 1043

You need to use it something like this.

$record = array();

foreach ($result as $key => $row)
{
      $query = // mysql query
      $rows = $query->result_array();
      $record[]['bookingId'] = $rows['0']['bookingId'];
      $record[]['userId'] = $rows['0']['userId'];
      $record[]['status'] = $rows['0']['status'];
}

echo "<pre>";print_R($record);

Basically, you're missing updating the index of the array.

Upvotes: 0

Юрий
Юрий

Reputation: 94

Don't you rewrite the value in the array every time?

$record = array();
foreach ($result as $key => $row) {
    $query = // mysql query
    $rows = $query->result_array();
    $record[] = [
        'bookingId' => $rows['0']['bookingId'],
        'userId' => $rows['0']['userId'],
        'status' => $rows['0']['status'],
    ];
}
echo "<pre>";
print_R($record);

Upvotes: 1

Related Questions