0

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?

1
  • Why? item_1 or item_2 is no more descriptive than 0 or 1. Commented Jun 23, 2020 at 0:00

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Or get the first row before the loop and array_combine with the following rows.
@AbraCadaver I was thinking of using array_combine, but didn't feel like writing it out. Didn't notice the header row.
@Aedan No, because post-increment returns the old value. You would be correct if I wrote ++$index
@Barmar What if I didn't have the header row in the CSV file? What would I use in place of array_combine?
You can just assign a variable like $cols = ["id", "name", "qty", "price"];
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.