Have array like this
Array
(
[] =>
[3837920201e05ba7c2fbffd3f1255129] => 'bg img a href Main | Delete etc'
[94ae40ff9b6df5bb123fb12211f48b11] => 'bg img a href Main | Delete etc'
[3974b3863e7ca7b7ea2026e44bbacfd2] => 'bg img a href Main | Delete etc'
)
Want to move key 3974b3863e7ca7b7ea2026e44bbacfd2
at top so array would look like
Array
(
[] =>
[3974b3863e7ca7b7ea2026e44bbacfd2] => 'bg img a href Main | Delete etc'
[3837920201e05ba7c2fbffd3f1255129] => 'bg img a href Main | Delete etc'
[94ae40ff9b6df5bb123fb12211f48b11] => 'bg img a href Main | Delete etc'
)
At first extract item that i want to be at top
$top_image = array_slice( $array, 2, 1 );
3974b3863e7ca7b7ea2026e44bbacfd2
is third element (as if key) in array (0,1,2)
Next want to create array $other_images
. Decided to remove the initial third element and then merge both arrays.
Trying to remove third element. Read [array_splice][1]
understand that first number (offset) is where i want to start to remove and second (length) - how many elements want to remove. So I tried
$top_image = array_splice( $array, 2, 1 );
But result is the same as with array_slice.
Then tried
foreach( $arr as $k => $val ){
if( $k != 2 ){
$other_images[] = $val;
}
}
Expect to see 2 remaining elements. But see all 3.
What is wrong? How to remove certain element from array?
Regarding foreach
$k
can not be equal to 2, because $k
is the long string... Tried for
, but also not suitable...
If you want to move the last element into the first place use array_pop, array_merge and a foreach trick to keep the key.
foreach($array as $key => $v) {}
$temp = [$key => array_pop($array)];
array_merge($temp, $array);
$array = $temp;
If it's not the last element and you know the key, it's unset that will help you.
// assume $key is set
$temp = [$key => $array[$key]];
unset($array[$key]);
array_merge($temp, $array);
$array = $temp;
Last elem ( 3974b3863e7ca7b7ea2026e44bbacfd2 => 'bg img a href Main | Delete etc'
) to top:
// last value to top
$last = array_pop($arr);
array_unshift($arr,$last);
Update
// last couple(key-value) to top
end($arr);
$last_key = key($arr);
$last_value = array_pop($arr);
$arr = array($last_key=>$last_value) + $arr;
var_dump($arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.