PHP - 在特定密钥之前快速获取先前数组元素的方法

问题描述:

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)
);

如何在特定数组键之前获取所有前一个元素。 p>

这是我的数组: p>

  $ key = 256; 
 
 $ array =(
125 => array(  571,570),
284 =>数组(567,566),
256 =>数组(562,560),
110 =>数组(565,563),
); 
  code  >  pre> 
 
 

现在我想要这样的结果: p>

  $ array =(
125 => array(571,570),\  n284 => array(567,566)
); 
  code>  pre> 
  div>

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));