Jump to content

For each loop not getting all data


Adamhumbug
Go to solution Solved by Barand,

Recommended Posts

I have a function that lists out all items that should appear on a quote - i know the sql is correct as when i was using a whille($stmt -> fetch()...... everything worked fine.

I am now building an array so that i can display it by a certain value but i am only getting 2 results output and there should be 16.

 $row = $stmt -> fetchAll();

    foreach($row as $item){
        if(isset($data[$item['sectionName']])){
            $data[$item['sectionName']] = [];
        }
        $data[$item['sectionName']][]= ["itemName" =>$item['name'], "quantity" => $item['quantity']];
    }

    foreach($data as $section => $items){
        $out.= "<br/>".$section."<br/>";
        foreach($items as $i){
            $out.= "-".$i['itemName'];
        }
    }

Below are the rows i am expecting to see.

Screenshot2023-08-18at13_24_30.png.ace72f847638a5413e3b3774db1bab16.png

This is what is being output using

$out = "<pre>".print_r($data,1)."</pre>";

 

Screenshot 2023-08-18 at 13.25.09.png

Edited by Adamhumbug
Link to comment
Share on other sites

1 hour ago, Adamhumbug said:
    foreach($row as $item){
        if(isset($data[$item['sectionName']])){
            $data[$item['sectionName']] = [];
        }
        $data[$item['sectionName']][]= ["itemName" =>$item['name'], "quantity" => $item['quantity']];
    }

this is just indexing/pivoting the data by a column. PDO has a fetch mode that will 'automatically' do that for you, assuming that the sectionName is the first column in the SELECT ... list -

$data = $stmt -> fetchAll(PDO::FETCH_GROUP);

if for some reason you require the name values to be referenced as itemName in the fetched data, assign it that name as an alias in the sql query.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.