简体   繁体   中英

How to programmatically create a multidimensional array using a while loop

I'm trying to use PHP to read through a CSV file and build arrays based on matches of a specific row. The CSV file contents look like this:

id, name, qty, price
1,Jeff,2,59,
2,Tom,3,36,
3,Lenny,2,25,
4,Tom,5,69,
5,Jeff,3,19,
6,Tom,2,75,

I'm using a 'while' loop to read through the CSV file:

while (($row = fgetcsv($h, 10000, ",")) !== FALSE) {

The idea is: If, while reading through the CSV file, a match is found with $row[1] like this...

if($row[1] == 'Tom') {

...an array is created that would look like this when the 'while loop' completes:

array(
'item_1' => array('id' => 2, 'name' => 'Tom', 'qty' => 3, 'price' => 36),
'item_2' => array('id' => 4, 'name' => 'Tom', 'qty' => 5, 'price' => 69),
'item_3' => array('id' => 6, 'name' => 'Tom', 'qty' => 2, 'price' => 75)
);

(The "item number" for the first element would need to start with "item_1" and increment by 1 as a new element is added).

If this is possible, what logic would need to be used?

Just assign an element to the result array.

$result = [];
$index = 1;
$cols = fgetcsv($h, ","); // get header row
while (($row = fgetcsv($h, 10000, ",")) !== FALSE) {
    if ($row[1] == 'Tom') {
        $result['item_' . $index++] = array_combine($cols, $row);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM