Jump to content

While + Array + For Each


jj20051

Recommended Posts

Hello,

 

In all the time I've used PHP I've never had to use an array for anything. Well in this case I think I have to and hopefully you'll give me some details as to how to do such.

 

I have a while() query which pulls categories from a database. The categories are used in a jquery to display products. The problem is I can't run both the category query and the product query at the same time and if the id's for the categories in the database aren't uniform (IE: 1, 2, 3, 4, 5, 6) then the script doesn't work. Thus I think I need to use an Array to store each of the id's from the category table and use a for_each() to pull the product data. However I'm unsure of how to do this because as far as I can tell you have to insert all of the data in an array at the same time instead of being able to insert one item at a time.

 

My code can be seen here: Click Here

 

Hopefully one of you knows how I should go about this.

Link to comment
https://forums.phpfreaks.com/topic/211008-while-array-for-each/
Share on other sites

You don't have to add data to an array all at once. Once you create it and you can append things to the end rather easily.

<?php
//create the array
$my_array=array();
//add an item to the end of the array
$my_array[] = $new_item;
?>

Note that you can also add items with a specific key (and modify existing items) with the format.

$my_array['key'] = $value;

 

Hope this helps. I'm not very familiar with jquery, but you might be able to use a joined query and not need any of this.

From the sound of it, you should be able to accomplish it with a JOIN query, but if not, you can add elements to an array. You can add one element at a time as below, or to add multiple elements, see the manual for array_push() and array_unshift().

 

<?php
$array = array('zero', 'one', 'two', 'three');
$array[] = 'four';
print_r($array); // Returns: Array ( [0] => zero [1] => one [2] => two [3] => three [4] => four ) 
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.