简体   繁体   中英

PHP - split array by key

I've got the following array, containing ordered but non consecutive numerical keys:

Array
(
    [4] => 2
    [5] => 3
    [6] => 1
    [7] => 2
    [8] => 1
    [9] => 1
    [10] => 1
)

I need to split the array into 2 arrays, the first array containing the keys below 5, and the other array consisting of the keys 5 and above. Please note that the keys may vary (eg 1,3,5,10), therefore I cannot use array_slice since I don't know the offset.

Do you know any simple function to accomplish this, without the need of using a foreach ?

Just found out array_slice has a preserve_keys parameter.

$a = [
    4 => 2,
    5 => 3,
    6 => 1,
    7 => 2,
    8 => 1,
    9 => 1,
    10 => 1
];

$desired_slice_key = 5;
$slice_position = array_search($desired_slice_key, array_keys($a));

$a1 = array_slice($a, 0, $slice_position, true);
$a2 = array_slice($a, $slice_position, count($a), true);

you could use array_walk, passing in the arrays you wish to add the keys to by reference using the use keyword - something along the lines of this should work:

$splitArray = [1 => 2, 3 => 1, 5 => 2, 7 => 1, 9 => 3, 10 => 1];

$lt5 = [];
$gt5 = [];

array_walk($splitArray, function(&$val, $key) use (&$lt5, &$gt5) {
    $key < 5 ? $lt5[] = $key : $gt5[] = $key;
});

var_dump($lt5, $gt5);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM