I have an array which contains list of pagrank values. Consider below array:
Array
(
[0] => stdClass Object
(
[pagerank] => 3
)
[1] => stdClass Object
(
[pagerank] => 1
)
[2] => stdClass Object
(
[pagerank] => R
)
[3] => stdClass Object
(
[pagerank] => 2
)
[4] => stdClass Object
(
[pagerank] => 7
)
)
I want to shift/move page rank with 'R' like:
[2] => stdClass Object
(
[pagerank] => R
)
to the end of array and it should be on last index of array?
Edit: The array key is unknown.
$item = $array[2];
unset($array[2]);
array_push($array, $item);
If the index is unknown:
foreach($array as $key => $val) {
if($val->pagerank == 'R') {
$item = $array[$key];
unset($array[$key]);
array_push($array, $item);
break;
}
}
If you don't want to modify the array while it is being iterated over just find the index then make the modifications.
$foundIndex = false;
foreach($array as $key => $val) {
if($val->pagerank == 'R') {
$foundIndex = $key;
break;
}
}
if($foundIndex !== false) {
$item = $array[$foundIndex];
unset($array[$foundIndex]);
array_push($array, $item);
}
Something like this?
$var = array(
'name' => 'thename',
'title' => 'thetitle',
'media' => 'themedia'
);
// Remove first element (the name)
$name = array_shift($var);
// Add it on to the end
$var['name'] = $name;
var_dump($var);
/*
array(3) {
["title"]=>
string(8) "thetitle"
["media"]=>
string(8) "themedia"
["name"]=>
string(7) "thename"
}
*/
Ref: http://forums.phpfreaks.com/topic/177878-move-array-index-to-end/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With