Hi, all! I want to take the first 5 records in array below, but I can’t. Can you help me? I don’t know name of this array, I’m only see it like table in database.
You can access each nested array using the automatically set numbered keys (with each array being the value). So in this case you could use a “for” loop to iterate through the first five sub-arrays:
Not sure I have read your request correctly, but it you only wanted the first 5 rows from the db in the first place, then you could have limited your db to only returning 5 with LIMIT.
$sql = "SELECT id
, name
, `desc`
, price
FROM
mytable
LIMIT 5";
** desc is a mysql protected word, hence it is quoted with backticks, presuming you ARE using mysql of course … If you are not using mysql then your RDBMS will have its own way of limiting the number of returned rows.
Can you show us how $products is created/defined? We understand you want to treat it as an array (modernW’s code did just that), however, since we don’t know how you are defining $products, it is impossible for us to tell you if the issue lies in looping through the records or with how you created $products.
My gut says, it is how your created $products, and that $products currently is NOT an array.
I also want to point out that StarLion’s suggestion is good too, and more likely you should be using LIMIT against your MySQL database (if that is what you are using), and using a second query to do the pagination by returning a COUNT of the products in the table.
You created a multi-dimensional array, the index of each array is numeric, since you didn’t specifically define a key, so it starts with 0 and goes to 15 (since you have 16 items).
$products[0] would store the data for broccoli, $products[1] contains the data for butter, etc.
Raju Gautam’s implementation of array_chunk is a good solution, it does require changing your code entirely to what he posted, but it does work well for this.