PHP Adding Values to a Nested Array

I am encountering some difficulties with retrieving the output from an array. Despite my efforts, I have not been able to determine why each portion of the array is not being assigned a proper index. I even attempted to introduce a counter variable in hopes of resolving this issue but unfortunately to no avail. As a newcomer to PHP, any guidance or assistance provided would be greatly valued.

foreach($dbh->query('SELECT n_productID, t_productName, t_categoryName FROM v_prodcatintersect') as $row) {
    $prodID=$row["n_productID"]; 
    $prodName=$row["t_productName"]; 
    $prodCategor=$row["t_categoryName"];
    $products=array(
        array(
            "prodID" => $prodID,
            "prodName" => $prodName,
            "prodCategor" => $prodCategor
        ),
    print_r($products);
}
for($i = 0, $size = sizeof($products); $i < $size; ++$i){
    echo "The product ID is ".$products[$i]["prodID"];
    echo " The product name is ".$products[$i]["prodName"];
    echo " Product Category ".$products[$i]["prodCategor"];
}

At present, the output from the array (as displayed by the print_r function) shows "Array ( [0] => Array ( [prodID] => 1 [prodName] => iPhone 4 [prodCategor] => Smartphones ) ) Array ( [0] => Array ( [prodID] => 2 [prodName] => Droid 3 [prodCategor] => Smartphones ) )". Consequently, the echoes produced only capture the second item out of two due to both having identical indices. Any advice on rectifying this indexing predicament would be warmly welcomed. Thank you for your assistance.

Answer №1

If you want to add a new item to an existing array, you can follow this syntax:

$products[] = array(
                'prodID'   => $prodID,
                'prodName' => $prodName,
                'prodCategor' => $prodCategor);

By using this method, a new entry will be added at the end of the current array. Therefore, after the foreach loop, $products will not be overwritten but will contain all the previous items. This approach allows you to iterate through $products correctly in your second for loop.

array(
  [0] => array(
           [prodID] => 1
           [prodName] => iPhone
           [prodCategor] => Smartphones)
  [1] => array(
           [prodID] => 2
           [prodName] => Droid
           [prodCategor] => Smartphones))

Answer №2

Here's a helpful tip - each time you add a sub-array to your multidimensional array, make sure to increment the key index using [].

$products[] = array(
  "prodID" => $prodID,
  "prodName" => $prodName,
  "prodCategory" => $prodCategory
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fluctuating updated site (ajax)

What method do you recommend for maintaining the data in a table on a page current? Currently, I am using a timer that connects to the server via ajax every 2 seconds to check for updates. Is there a way to trigger an event or function only when the cont ...

Having difficulty accessing a JSON imported object beyond the FOR loop

I am facing an issue when trying to reference my imported JSON data. The problem arises when I attempt to access the data outside of a FOR loop, resulting in the error message "Uncaught TypeError: Cannot read property 'Tname' of undefined" The f ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...

When using PHP, JavaScript, and HTML, you can trigger an image upload immediately after choosing a file using the

I currently have a small form with two buttons - one for browsing and another for uploading an image. I feel that having two separate buttons for this purpose is unnecessary. Is there a way to combine the browse and upload functions into just one button? ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

What is the process for sharing your website content on Google Blogger?

I am currently developing a dashboard for a small business website and I would like to implement a feature that allows users to post directly to their Blogger blog from the dashboard of their own website. This eliminates the hassle of having to switch betw ...

Melodic Streaming Platform

I currently have a client-side application built using React. I have a collection of music stored on my Google Drive that I would like to stream online continuously. I lack experience in server-side programming. Can you suggest any resources or steps I s ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

The JQUERY code for refreshing a div requires a timeout delay

I'm looking for a way to refresh a specific div on my website that's used for chat. Here's the code I currently have: var refreshId = setInterval(function() { $('#chat_grab').load('chat_grab.php?randval=' + Math.rand ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

Switch up the key while iterating through a JSON object

Can you modify the key while iterating through objects using an external variable? Picture it like this: var data = [{ "id": 1, "name": "Simon", "age": 13 }, { "id": 2, "name": "Helga", "age": 18 }, { "id": 3, "name": "Tom ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered: javascript: var data = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protect ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...