PHP can I do this loop?
I have a loop (based on an array - which could grow but NOT too much - max 6 keys) e.g.: array('12','34','56',48')
. What I would like to do is loop through the array and THEN loop again to find the "previous" array val.
For example, key[0] = 12
, key[1] = 34
then key[0] = 12
, key[2] = 56
then key[1] = 34
etc.
The values of the array are ID's from a DB and I need (hopefully) to run a query based on the "curre开发者_Python百科nt key" and the previous key.
Any ideas - can it be done?
$num_elem = count($array);
for ($i = 0; $i < $num_elem; $i++)
{
$curr_val = $array[$i];
$prev_val = ( 0 == $i) ? null: $array[$i-1];
}
Unlike the other solutions, I would recommend against using an index based accessor.
In php, the keys are not necessarily in order. For example, if you call natsort
on your array, the key=>value
relationships stay the same but the array itself is actually reordered, leading to counterintuitive results. (See Why isn't natsort (or natcasesort) working here?)
I would use something like:
<?php
$ids = array('12','34','56','48');
$previous = false;
foreach($ids as $id)
{
echo "current: $id\n";
echo "previous: $previous\n";
$previous = $id;
}
?>
I don't think multiple loops are really needed here. I would use the internal pointer of the array with next()
, prev()
, and current()
functions.
If I've understood correctly you want to do this.
for($i=1; $i < count($array); $i++) {
$currentValue = $array[$i];
$previousValue = $array[$i-1];
// Here you can run a query based on the current and the previous value
}
For example, taking $array
as array(12,34,56,48)
you would have 3 iterations where the $currentValue
and $previousValue
would have the following values:
- First iteration: $currentValue = 34, $previousValue = 12
- Second iteration: $currentValue = 56, $previousValue = 34
- Third iteration: $currentValue = 48, $previousValue = 56
<?
$val = 56;
$data = array(12, 34, 12, 56, 34);
for($i = 0; $i < count($data); $i++) {
if($data[$i] == $val) {
if($i == 0) die("No previous");
$previous = $data[$i-1];
}
}
echo "Previous to $val was $previous";
or better yet use array_search() to find index for given $val
精彩评论