How can I get all previous element before a specific array key.
Here is my array:
$key = 256;
$array = (
125 => array(571, 570),
284 => array(567, 566),
256 => array(562, 560),
110 => array(565, 563),
);
Now I want result like this:
$array = (
125 => array(571, 570),
284 => array(567, 566)
);
You can iterate through and push values to a newArray
until you hit the key you are searching for:
$Key = 256;
$array = array(
"125" => array(571, 570),
"284" => array(567, 566),
"256" => array(562, 560),
"110" => array(565, 563),
);
$newArray = [];
foreach($array as $key => $value)
{
if($key == $Key) break;
$newArray[$key] = $value;
}
print_r ($newArray);
/*
=> Array (
[125] => Array ( [0] => 571 [1] => 570 )
[284] => Array ( [0] => 567 [1] => 566 )
)
*/
Get the numeric index of key first using array_search()
and array_keys()
. Then slice the array from the beginning to key's index using array_slice()
$index = array_search($key, array_keys($array)); // Get the numeric index of search key
$result = array_slice($array, 0, $index, true); // Slice from 0 up to index
print_r($result); // Print result
You can do this weird thing:
$key = 256;
$array = array(
125 => array(571, 570),
284 => array(567, 566),
256 => array(562, 560),
110 => array(565, 563),
);
print_r(array_slice($array, array_search($key, array_keys($array)), null, true));
Outputs
Array
(
[256] => Array
(
[0] => 562
[1] => 560
)
[110] => Array
(
[0] => 565
[1] => 563
)
)
UPDATE
I realize now that I look again, I did it backwards. I call dyslexic
moment... To do it the right way is like this
print_r(array_slice($array, 0, array_search($key, array_keys($array)),true));
$position = array_search($key, array_keys($array));
$output = array_slice($array, 0, $position);
print_r($output);
DEMO: https://3v4l.org/nmnDv
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.