I'm trying to get the smallest value of start and the biggest value of end outoff the object below. The object is an result of a sql script.
object(CI_DB_mysql_result)[18]
public 'conn_id' => resource(54, mysql link persistent)
public 'result_id' => resource(61, mysql result)
public 'result_array' =>
array (size=0)
empty
public 'result_object' =>
array (size=3)
0 =>
object(stdClass)[16]
public 'id' => string '601' (length=3)
public 'scheduled' => string '0' (length=1)
public 'start' => string '2014-10-17 06:00:00' (length=19)
public 'end' => string '2014-10-17 11:00:00' (length=19)
1 =>
object(stdClass)[19]
public 'id' => string '602' (length=3)
public 'scheduled' => string '0' (length=1)
public 'start' => string '2014-10-17 18:00:00' (length=19)
public 'end' => string '2014-10-17 19:30:00' (length=19)
2 =>
object(stdClass)[20]
public 'id' => string '603' (length=3)
public 'scheduled' => string '1' (length=1)
public 'start' => string '2014-10-17 11:00:00' (length=19)
public 'end' => string '2014-10-17 18:00:00' (length=19)
public 'custom_result_object' =>
array (size=0)
empty
public 'current_row' => int 0
public 'num_rows' => int 3
public 'row_data' => null
In this case the smallest value of start = '2014-10-17 06:00:00' and the biggest value of end = '2014-10-17 19:30:00'. So the result I'm looking for looks like this:
$smallest_start_value = '2014-10-17 06:00:00';
$biggest_end_value = '2014-10-17 19:30:00';
How should the code look like, in order to compute this result?
Function:
function unschedule_resource() {
$event_id = 4;//$_POST['event_id'];
$event_start = '2014-10-17 11:00:00';//$_POST['event_start'];
$event_end = '2014-10-17 18:00:00';//$_POST['event_end'];
// Get resource id
$this->db->select('
event.resource_id'
);
$this->db->from('promo_manager.event');
$this->db->where('event.id =', $event_id);
$data = $this->db->get();
foreach ($data->result() as $row) {
echo $row->resource_id . "<br>";
$resource_id = $row->resource_id;
}
// Get resource events to unschedule
$this->db->select('
resource_calendar.id,
resource_calendar.scheduled,
resource_calendar.start,
resource_calendar.end'
);
$this->db->from('promo_manager.resource_calendar');
$this->db->where('resource_calendar.resource_id =', $resource_id);
$this->db->where('resource_calendar.start =', $event_start);
$this->db->where('resource_calendar.end =', $event_end);
$this->db->or_where('resource_calendar.end =', $event_start);
$this->db->or_where('resource_calendar.start =', $event_end);
$data = $this->db->get();
$lowest_value = null;
$highest_value = null;
foreach ($data as $the_key => $the_value) {
if ($the_key == 'start') {
if ($lowest_value === null) {
$lowest_value = $the_value;
}
if ($the_value < $lowest_value) {
$lowest_value = $the_value;
}
}
}
//echo $lowest_value;
var_dump ($lowest_value) ;
}
The code of Sam should look like this:
$lowest_value = null;
$highest_value = null;
foreach($data as $obj) { //$data should be the array containing the result objects.
$start = $obj->start;
$end = $obj->end;
if ($lowest_value === null)
$lowest_value = $start;
else
if ($lowest_value > $start)
$lowest_value = $start;
if ($highest_value === null)
$highest_value = $end;
else
if ($highest_value < $end)
$highest_value = $end;
}
can be shortened to :
if ($lowest_value === null || $lowest_value > $start)
$lowest_value = $start;
if ($highest_value === null || $highest_value < $end)
$highest_value = $end;
Both values can be generated within one iteration without problems. Keep in mind that the < and > works in the case you keep the date formated as given. Otherwhise you would need to use date-functionality to compare the dates.
You could also use MySQL to query directly for the Min/Max values using the Aggregation methods Min or Max: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
(If you don't need each object to be loaded this will be faster)
I'm not sure if there's a way you couldn't do this in the select statement or not, I'll assume not. Get your result object into an array. This is super basic but should get the job done.
$lowest_value = null;
$highest_value = null;
foreach(result_object as $the_key => $the_value) {
if($the_key == 'start') {
if($lowest_value === null) {
$lowest_value = $the_value;
}
if(the_value < $lowest_value) {
$lowest_value = $the_value;
}
}
}
Do a second check for the end value just changing the operator
Related
Can someone help me, where should I put my $days[] array so that holidays are not included in this array.
My code is as follows
$data['ferie'] = $this->CalendrierModel->find('ferie');
$timestamp = strtotime ('2020-05-18');
$days = array();
$i = 0;
$jourOuvre = 5;
foreach($data['ferie'] as $row){
$ferie = array($row->start);
while($i < $jourOuvre){
$date_tmp = date("Y-m-d", strtotime($i . 'weekdays', $timestamp));
if (in_array($date_tmp , $ferie)){
$jourOuvre++;
$date_tmp = date("Y-m-d", strtotime('+1days', $date_tmp));
}
$days[] = $date_tmp;
$i++;
}
}
var_dump($days);
this code makes :
699:
array (size=5)
0 => string '2020-05-18' (length=10)
1 => string '2020-05-19' (length=10)
2 => string '2020-05-20' (length=10)
3 => string '2020-05-21' (length=10)
4 => string '2020-05-22' (length=10)
while 2020-05-21 is a holiday.
NB: $data['ferie'] is an array of holidays.
Thanks, guys. I did it.
$data['ferie'] = $this->CalendrierModel->find('ferie');
$timestamp = strtotime ('2020-05-18');
$days = array();
$ferie = array();
$i = 0;
$jourOuvre = 5;
foreach($data['ferie'] as $row){
$ferie[] = $row->start;
}
while($i < $jourOuvre){
$date_tmp = date("Y-m-d", strtotime($i . ' weekdays' , $timestamp));
if(in_array($date_tmp , $ferie)) {
$jourOuvre++;
} else {
$days[] = $date_tmp;
}
$i++;
}
var_dump($days);
Holidays are out of my array :
C:\wamp\www\HELPJUR\application\controllers\Ticket.php:816:
array (size=5)
0 => string '2020-05-18' (length=10)
1 => string '2020-05-19' (length=10)
2 => string '2020-05-20' (length=10)
3 => string '2020-05-22' (length=10)
4 => string '2020-05-25' (length=10)
For my codes, When I select the checkbox, it will retrieve the date and price from database and do a calculation to get a total price.
But it update all rows with the same value.
I had tried to select 3 checkbox, and var_dump the total price, and the results are correct.
But I want to update into database, it updated all rows with the same value.
Controller:
$PledgeCheckbox = ($this->input->post('batch_pledge[]') ? '1' : '0');
//$Pledge_No = $this->input->post('batch_pledge[]'); //return value of pledge_id
if($PledgeCheckbox == '1'){
$Pledge_No = $this->input->post('batch_pledge[]'); //return value of pledge_id
//take the stg_fee_per_mth from database and calculate $Total_Stg_Fee
$Pledge = $this->pledge->GetPledgeStgFee($Pledge_No);
foreach($Pledge as $row){
$Stg_fee_per_mth = $row->stg_fee_per_mth;
$Pledge_date = $row->pledge_date;
$DATE_NOW = strtotime($Cur_date);
$DATE_PREV = strtotime($Pledge_date);
$Year1 = date('y', $DATE_NOW);
$Year2 = date('y', $DATE_PREV);
$Month_Now = date('m', $DATE_NOW);
$Month_Prev = date('m', $DATE_PREV);
$Month_diff = (($Year1 - $Year2)*12)+($Month_Now - $Month_Prev);
if($Month_diff !== 0){
$Total_Stg_Fee = $Stg_fee_per_mth * $Month_diff;
//update $Total_Stg_fee in database
$this->pledge->UpdatePledgeTotalStgFee($Total_Stg_Fee,$Month_diff);
//var_dump($Total_Stg_Fee);
}else{
//if $Month_diff == 0, $Stg_fee_per_mth must multiple with 1, if not $Total_stg_Fee will become 0
$Month_diff = 1;
$Total_Stg_Fee = $Stg_fee_per_mth * 1;
//update $Total_Stg_fee in database
$this->pledge->UpdatePledgeTotalStgFee($Total_Stg_Fee,$Month_diff);
//var_dump($Total_Stg_Fee);
}
}
$data['pledge'] = $this->pledge->FetchPledge2Renew($Pledge_No);
$this->load->view('auth/header',$data);
$this->load->view('pledge/batch_renew_pledge',$data);
$this->load->view('pledge/footer',$data);
}
Model:
public function UpdatePledgeTotalStgFee($Total_Stg_Fee,$Month_diff){
$post = $this->input->post();
//$Month_diff = $post;
//$Total_Stg_Fee = $post;
foreach($post['batch_pledge'] as $k => $value){
$TotalStgFee[] = array(
'pledge_id' => $value,
'no_of_mth' => $Month_diff,
'total_stg_fee' => $Total_Stg_Fee
);
}
$this->db->update_batch('pledge',$TotalStgFee,'pledge_id'); //('table','array','condition')
}
output of var_dump($TotalStgFee)
C:\wamp64\www\kde\store\application\models\Pledge_model.php:683:
array (size=2)
0 =>
array (size=3)
'pledge_id' => string '27' (length=2)
'no_of_mth' => int 1
'total_stg_fee' => float 20
1 =>
array (size=3)
'pledge_id' => string '21' (length=2)
'no_of_mth' => int 1
'total_stg_fee' => float 20
C:\wamp64\www\kde\store\application\models\Pledge_model.php:683:
array (size=2)
0 =>
array (size=3)
'pledge_id' => string '27' (length=2)
'no_of_mth' => int 36
'total_stg_fee' => float 900
1 =>
array (size=3)
'pledge_id' => string '21' (length=2)
'no_of_mth' => int 36
'total_stg_fee' => float 900
To iterate a posted checkbox input, it's better to use foreach instead of for loop since the $post['pledge_id'] array index is not always sequential. I've changed your codes to just call the update method only once after the foreach loop :
Controller :
$PledgeCheckbox = ($this->input->post('batch_pledge[]') ? '1' : '0');
//$Pledge_No = $this->input->post('batch_pledge[]'); //return value of pledge_id
if($PledgeCheckbox == '1'){
$Pledge_No = $this->input->post('batch_pledge[]'); //return value of pledge_id
//take the stg_fee_per_mth from database and calculate $Total_Stg_Fee
$Pledge = $this->pledge->GetPledgeStgFee($Pledge_No);
if (!empty($Pledge)) {
$Total_Stg_Fee = [];
$Month_diff = [];
foreach($Pledge as $k => $row){
$Stg_fee_per_mth = $row->stg_fee_per_mth;
$Pledge_date = $row->pledge_date;
$DATE_NOW = strtotime($Cur_date);
$DATE_PREV = strtotime($Pledge_date);
$Year1 = date('y', $DATE_NOW);
$Year2 = date('y', $DATE_PREV);
$Month_Now = date('m', $DATE_NOW);
$Month_Prev = date('m', $DATE_PREV);
$Month_diff[$k] = (($Year1 - $Year2)*12)+($Month_Now - $Month_Prev);
if($Month_diff[$k] !== 0){
$Total_Stg_Fee[$k] = $Stg_fee_per_mth * $Month_diff[$k];
//update $Total_Stg_fee in database
// $this->pledge->UpdatePledgeTotalStgFee($Total_Stg_Fee,$Month_diff);
//var_dump($Total_Stg_Fee);
}else{
//if $Month_diff == 0, $Stg_fee_per_mth must multiple with 1, if not $Total_stg_Fee will become 0
$Month_diff[$k] = 1;
$Total_Stg_Fee[$k] = $Stg_fee_per_mth * 1;
//update $Total_Stg_fee in database
// $this->pledge->UpdatePledgeTotalStgFee($Total_Stg_Fee,$Month_diff);
//var_dump($Total_Stg_Fee);
}
}
$this->pledge->UpdatePledgeTotalStgFee($Pledge_No,$Total_Stg_Fee,$Month_diff);
}
$data['pledge'] = $this->pledge->FetchPledge2Renew($Pledge_No);
$this->load->view('auth/header',$data);
$this->load->view('pledge/batch_renew_pledge',$data);
$this->load->view('pledge/footer',$data);
}
Model :
public function UpdatePledgeTotalStgFee($Pledge_No,$Total_Stg_Fee,$Month_diff){
// $post = $this->input->post();
//$Month_diff = $post;
//$Total_Stg_Fee = $post;
// $arraySize = count($post['pledge_id']);
/*
for($k=0; $k<$arraySize; $k++){
$TotalStgFee[] = array(
'pledge_id' => $post['pledge_id'][$k],
'no_of_mth' => $Month_diff.[$k],
'total_stg_fee' => $Total_Stg_Fee.[$k]
);
}
*/
$TotalStgFee = [];
foreach($Pledge_No as $k => $value){
$TotalStgFee[$k] = array(
'pledge_id' => $value,
'no_of_mth' => $Month_diff[$k],
'total_stg_fee' => $Total_Stg_Fee[$k]
);
}
$this->db->update_batch('pledge',$TotalStgFee,'pledge_id'); //('table','array','condition')
}
This will save each $Total_Stg_Fee and $Month_diff as an array first, then insert it as batch insert. I've also added $Pledge_No as a parameter on the UpdatePledgeTotalStgFee() function and passing it to the model.
Im trying to build a little site using XML instead of a database.
I would like to build a next and prev button which will work relative to the content I have displayed.
I found the php function next() and prev() as well as current() but I do not know how to set the pointer to a specific position to be able to navigate relative to the current page.
$list=array('page1','page2','page3')
eg if im displaying contents of page2 how could I tell php i am at $list[1] so that next($list) shows page3?
Thanks in advance
If your array is always indexed consistently (eg. 'page1' is always at index '0'), it's fairly simple:
$List = array('page1', 'page2', 'page3', 'page4', 'page5');
$CurrentPage = 3; // 'page4'
while (key($List) !== $CurrentPage) next($List); // Advance until there's a match
I personally don't rely on automatic indexing because there's always a chance that the automatic index might change. You should consider explicitly defining the keys:
$List = array(
'1' => 'page1',
'2' => 'page2',
'3' => 'page3',
);
EDIT: If you want to test the values of the array (instead of the keys), use current():
while (current($List) !== $CurrentPage) next($List);
Using the functions below, you can get the next and previous values of the array.
If current value is not valid or it is the last (first - for prev) value in the array, then:
the function getNextVal(...) returns the first element value
the function getPrevVal(...) returns the last element value
The functions are cyclic.
function getNextVal(&$array, $curr_val)
{
$next = 0;
reset($array);
do
{
$tmp_val = current($array);
$res = next($array);
} while ( ($tmp_val != $curr_val) && $res );
if( $res )
{
$next = current($array);
}
return $next;
}
function getPrevVal(&$array, $curr_val)
{
end($array);
$prev = current($array);
do
{
$tmp_val = current($array);
$res = prev($array);
} while ( ($tmp_val != $curr_val) && $res );
if( $res )
{
$prev = current($array);
}
return $prev;
}
Using the functions below, you can get the next and previous KEYs of the array.
If current key is not valid or it is the last (first - for prev) key in the array, then:
the function getNext(...) returns 0 (the first element key)
the function getPrev(...) returns the key of the last array element
The functions are cyclic.
function getNext(&$array, $curr_key)
{
$next = 0;
reset($array);
do
{
$tmp_key = key($array);
$res = next($array);
} while ( ($tmp_key != $curr_key) && $res );
if( $res )
{
$next = key($array);
}
return $next;
}
function getPrev(&$array, $curr_key)
{
end($array);
$prev = key($array);
do
{
$tmp_key = key($array);
$res = prev($array);
} while ( ($tmp_key != $curr_key) && $res );
if( $res )
{
$prev = key($array);
}
return $prev;
}
The internal array pointer is mainly used for looping over an array within one PHP script. I wouldn't recommend using it for moving from page to page.
For that, just keep track of the page number and the page size (number of items per page). Then, when you're loading another page, you can use them to decide which array items to show. For example:
$pageNum = $_GET["pageNum"];
$pageSize = 10;
$startIndex = ($pageNum - 1) * $pageSize;
$endIndex = ($startIndex + $pageSize) - 1;
(or something similar)
another aproach without loops or search.
list($prev,$next) = getPrevNext($oObjects,$sCurrentKey);
function getPrevNext($aArray,$key){
$aKeys = array_keys($aArray); //every element of aKeys is obviously unique
$aIndices = array_flip($aKeys); //so array can be flipped without risk
$i = $aIndices[$key]; //index of key in aKeys
if ($i > 0) $prev = $aArray[$aKeys[$i-1]]; //use previous key in aArray
if ($i < count($aKeys)-1) $next = $aArray[$aKeys[$i+1]]; //use next key in aArray
return array($prev,$next);
}
I use this code for set internal pointer with key of array.
reset($List);
while (key($List) !== $id && key($List) !== null) next($List);
if(key($List) === null) end($List);
After that you can use prev() or next().
Update follow notice from #VaclavSir
Try this
public function getNextVal(&$array, $curr_val){
foreach($array as $k=>$v){
if($v['your_key'] == $curr_val){
if(isset($array[$k+1]))
return $array[$k+1];
else
return $array[0];
}
}
}
public function getPrevVal(&$array, $curr_val){
foreach($array as $k=>$v){
if($v['your_key'] == $curr_val){
if(isset($array[$k-1]))
return $array[$k-1];
else
return end($array);
}
}
}
for array like this:
array (size=3)
0 =>
array (size=11)
'id' => string '21' (length=2)
'cat' => string '1' (length=1)
'gal' => string '1' (length=1)
'type' => string 'image' (length=5)
'name' => string 'chalk_art_dies-irea_2nd_pic' (length=27)
'permalink' => string 'chalk-art-dies-irea-2nd-pic' (length=27)
'url' => string 'rxNsPoEiJboJQ32.jpg' (length=19)
'content' => string '' (length=0)
'date' => string '1432076359' (length=10)
'order' => string '20' (length=2)
'views' => string '0' (length=1)
1 =>
array (size=11)
'id' => string '10' (length=2)
'cat' => string '1' (length=1)
'gal' => string '1' (length=1)
'type' => string 'image' (length=5)
'name' => string '3dchalkart' (length=10)
'permalink' => string '3dchalkart' (length=10)
'url' => string 's57i5DKueUEI4lu.jpg' (length=19)
'content' => string '' (length=0)
'date' => string '1432076358' (length=10)
'order' => string '9' (length=1)
'views' => string '0' (length=1)
2 =>
current and next functions are deprecated for objects since PHP 8.1
Here is a way to do it using ArrayIterator
Keys
$list = new ArrayIterator(array('page1', 'page2', 'page3'));
$currentPage = 1;
$list->seek($currentPage);
echo $list->current(); // 'page2'
Values
$list = new ArrayIterator(array('page1', 'page2', 'page3'));
while ($list->current() !== 'page2') {
$list->next();
}
echo $list->current(); // 'page2'
Here's the complete #tjunglc 's approach with looping:
protected function getPrevNext($aArray,$key)
{
$aKeys = array_keys($aArray); //every element of aKeys is obviously unique
$aIndices = array_flip($aKeys); //so array can be flipped without risk
$i = $aIndices[$key]; //index of key in aKeys
if ($i > 0) $prev = $aArray[$aKeys[$i-1]]; //use previous key in aArray
if ($i < count($aKeys)-1) $next = $aArray[$aKeys[$i+1]]; //use next key in aArray
if (!isset($prev)) $prev = end($aArray);
if (!isset($next)) $next = reset($aArray);
return array($prev,$next);
}
Oh and thankx #tjunglc for this :)
I am a newbie and have an issue in parsing json.
Below is the json array I want to parse:
array (size=3)
'status' => string 'success' (length=7)
'message' => string '' (length=0)
'data' =>
array (size=2)
0 =>
array (size=2)
'asset' => string 'ONESATOSHI' (length=10)
'balance' => string '0.0000001' (length=9)
1 =>
array (size=2)
'asset' => string 'XCP' (length=3)
'balance' => string '150333.69737005' (length=15)
I want to get the balance of array 1.
I have tried this:
function xcp_balance($wallet)
{
$jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
$balance = $jarr['data'][1]['balance'];
if (is_numeric($balance)) {
return $balance;
} else {
return 0;
}
}
$wallet = '1NFeBp9s5aQ1iZ26uWyiK2AYUXHxs7bFmB';
xcp_balance($wallet);
But it not working. Kindly help me and apologies for my language.
Its working. You just forgot to echo the returned value:
function xcp_balance($wallet) {
$jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
$balance = $jarr['data'][1]['balance'];
if (is_numeric($balance)) {
return $balance;
} else {
return 0;
}
}
$wallet = '1NFeBp9s5aQ1iZ26uWyiK2AYUXHxs7bFmB';
echo xcp_balance($wallet); // 150333.69737005
// ^ echo it
Working here
And it might be better to check the existence of that index first:
function xcp_balance($wallet) {
$jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
$balance = (isset($jarr['data'][1]['balance']) && is_numeric($jarr['data'][1]['balance']) ? $jarr['data'][1]['balance'] : 0);
return $balance;
}
Im trying to build a little site using XML instead of a database.
I would like to build a next and prev button which will work relative to the content I have displayed.
I found the php function next() and prev() as well as current() but I do not know how to set the pointer to a specific position to be able to navigate relative to the current page.
$list=array('page1','page2','page3')
eg if im displaying contents of page2 how could I tell php i am at $list[1] so that next($list) shows page3?
Thanks in advance
If your array is always indexed consistently (eg. 'page1' is always at index '0'), it's fairly simple:
$List = array('page1', 'page2', 'page3', 'page4', 'page5');
$CurrentPage = 3; // 'page4'
while (key($List) !== $CurrentPage) next($List); // Advance until there's a match
I personally don't rely on automatic indexing because there's always a chance that the automatic index might change. You should consider explicitly defining the keys:
$List = array(
'1' => 'page1',
'2' => 'page2',
'3' => 'page3',
);
EDIT: If you want to test the values of the array (instead of the keys), use current():
while (current($List) !== $CurrentPage) next($List);
Using the functions below, you can get the next and previous values of the array.
If current value is not valid or it is the last (first - for prev) value in the array, then:
the function getNextVal(...) returns the first element value
the function getPrevVal(...) returns the last element value
The functions are cyclic.
function getNextVal(&$array, $curr_val)
{
$next = 0;
reset($array);
do
{
$tmp_val = current($array);
$res = next($array);
} while ( ($tmp_val != $curr_val) && $res );
if( $res )
{
$next = current($array);
}
return $next;
}
function getPrevVal(&$array, $curr_val)
{
end($array);
$prev = current($array);
do
{
$tmp_val = current($array);
$res = prev($array);
} while ( ($tmp_val != $curr_val) && $res );
if( $res )
{
$prev = current($array);
}
return $prev;
}
Using the functions below, you can get the next and previous KEYs of the array.
If current key is not valid or it is the last (first - for prev) key in the array, then:
the function getNext(...) returns 0 (the first element key)
the function getPrev(...) returns the key of the last array element
The functions are cyclic.
function getNext(&$array, $curr_key)
{
$next = 0;
reset($array);
do
{
$tmp_key = key($array);
$res = next($array);
} while ( ($tmp_key != $curr_key) && $res );
if( $res )
{
$next = key($array);
}
return $next;
}
function getPrev(&$array, $curr_key)
{
end($array);
$prev = key($array);
do
{
$tmp_key = key($array);
$res = prev($array);
} while ( ($tmp_key != $curr_key) && $res );
if( $res )
{
$prev = key($array);
}
return $prev;
}
The internal array pointer is mainly used for looping over an array within one PHP script. I wouldn't recommend using it for moving from page to page.
For that, just keep track of the page number and the page size (number of items per page). Then, when you're loading another page, you can use them to decide which array items to show. For example:
$pageNum = $_GET["pageNum"];
$pageSize = 10;
$startIndex = ($pageNum - 1) * $pageSize;
$endIndex = ($startIndex + $pageSize) - 1;
(or something similar)
another aproach without loops or search.
list($prev,$next) = getPrevNext($oObjects,$sCurrentKey);
function getPrevNext($aArray,$key){
$aKeys = array_keys($aArray); //every element of aKeys is obviously unique
$aIndices = array_flip($aKeys); //so array can be flipped without risk
$i = $aIndices[$key]; //index of key in aKeys
if ($i > 0) $prev = $aArray[$aKeys[$i-1]]; //use previous key in aArray
if ($i < count($aKeys)-1) $next = $aArray[$aKeys[$i+1]]; //use next key in aArray
return array($prev,$next);
}
I use this code for set internal pointer with key of array.
reset($List);
while (key($List) !== $id && key($List) !== null) next($List);
if(key($List) === null) end($List);
After that you can use prev() or next().
Update follow notice from #VaclavSir
Try this
public function getNextVal(&$array, $curr_val){
foreach($array as $k=>$v){
if($v['your_key'] == $curr_val){
if(isset($array[$k+1]))
return $array[$k+1];
else
return $array[0];
}
}
}
public function getPrevVal(&$array, $curr_val){
foreach($array as $k=>$v){
if($v['your_key'] == $curr_val){
if(isset($array[$k-1]))
return $array[$k-1];
else
return end($array);
}
}
}
for array like this:
array (size=3)
0 =>
array (size=11)
'id' => string '21' (length=2)
'cat' => string '1' (length=1)
'gal' => string '1' (length=1)
'type' => string 'image' (length=5)
'name' => string 'chalk_art_dies-irea_2nd_pic' (length=27)
'permalink' => string 'chalk-art-dies-irea-2nd-pic' (length=27)
'url' => string 'rxNsPoEiJboJQ32.jpg' (length=19)
'content' => string '' (length=0)
'date' => string '1432076359' (length=10)
'order' => string '20' (length=2)
'views' => string '0' (length=1)
1 =>
array (size=11)
'id' => string '10' (length=2)
'cat' => string '1' (length=1)
'gal' => string '1' (length=1)
'type' => string 'image' (length=5)
'name' => string '3dchalkart' (length=10)
'permalink' => string '3dchalkart' (length=10)
'url' => string 's57i5DKueUEI4lu.jpg' (length=19)
'content' => string '' (length=0)
'date' => string '1432076358' (length=10)
'order' => string '9' (length=1)
'views' => string '0' (length=1)
2 =>
current and next functions are deprecated for objects since PHP 8.1
Here is a way to do it using ArrayIterator
Keys
$list = new ArrayIterator(array('page1', 'page2', 'page3'));
$currentPage = 1;
$list->seek($currentPage);
echo $list->current(); // 'page2'
Values
$list = new ArrayIterator(array('page1', 'page2', 'page3'));
while ($list->current() !== 'page2') {
$list->next();
}
echo $list->current(); // 'page2'
Here's the complete #tjunglc 's approach with looping:
protected function getPrevNext($aArray,$key)
{
$aKeys = array_keys($aArray); //every element of aKeys is obviously unique
$aIndices = array_flip($aKeys); //so array can be flipped without risk
$i = $aIndices[$key]; //index of key in aKeys
if ($i > 0) $prev = $aArray[$aKeys[$i-1]]; //use previous key in aArray
if ($i < count($aKeys)-1) $next = $aArray[$aKeys[$i+1]]; //use next key in aArray
if (!isset($prev)) $prev = end($aArray);
if (!isset($next)) $next = reset($aArray);
return array($prev,$next);
}
Oh and thankx #tjunglc for this :)