Reputation: 38
I have a query that returns data from a database and stores the data in an array called $array
.
Using a print_r($array)
I receive data like:
Array
(
[0] => stdClass Object
(
[Item1] => 1
[Item2] => 1
[Item3] => 1
[Item4] => 'Az'
[Item5] => 222
[Item6] => 223
[Item7] => 21
[Item8] => 22
)
)
I've found I can return the keys Item1
to Item8
using:
foreach ($array[0] as $key => $a){
echo '<pre>', $key, '</pre>';
}
However I'd only like to return from Item4 to the end of the array. (remove the first 3 items)
Note that query sometimes returns multiple rows i.e. $array[0]
, $array[1]
but $array[0]
will always exist if there's a result. I only need to get the keys from the array once as I'd like to use them as column headings in the table they are displayed in.
I would prefer a foreach()
situation as I would only like to output as many columns as are present.
I've tried looking at array_slice()
but I couldn't seem to get it to work, my efforts are displayed below:
$sliced = array_slice($prices[0], 3, $preserve_keys = true);
foreach ($sliced as $key => $value){
echo '<pre>'.$key.'</pre>';
}
Upvotes: 0
Views: 39
Reputation: 16055
The solution to Your problem lays deeper than You are trying to solve it.
If the DB query returns an array with indexes 1..10 but You only want to display the data from index 4..10 then what You really need is to change the DB query to return only these columns 4..10.
So basically instead of executing this query:
SELECT * FROM table1
You need to execute query such this:
SELECT col4, col5, col6, col7, col8, col9, col10
FROM table1
Upvotes: 1
Reputation: 20469
As you mention "i would prefer a foreach solution...", you can simply increment a counter, and not output anything until the counter has reached the required value:
$count = 0
foreach ($array[0] as $key => $a){
$count++;
if($count > 3){
echo '<pre>', $key, '</pre>';
}
}
Upvotes: 1
Reputation: 5332
Transform your stdClass
object into array and use array_slice
.
$neededItems = array_slice((array)$array[0], 4, null, true);
Upvotes: 1