我有一个普通的、无聊的旧数组,里面有很多数据。假设数组的结构是这样的:
$myArray = array( 'a','b','c','START','d','e','f','END' );
现在,我只需要选择START之后、END之前的值。因此,在本例中,我需要选择值"d"、"e"answers"f"。
这是棘手的部分;START将始终存在,但END可能存在,也可能不存在(这就是从服务器返回数据的方式)。如果START和END都存在,那么我只需要2之间的值。如果只存在START,那么只需从START中选择所有值,直到数组结束。'START’没有固定索引;其位置根据服务器提供的数据而变化。
那么,有什么快速、相对无痛的方法可以在2个指定值之间提取这些值,然后将它们保存到一个新数组中呢?
编辑:我唯一能发挥作用的实现是@nicklb提供的,在评论中更详细。为了便于他人使用,我已将其添加到此OP中。
array_shift( $array[0]); // Get rid of the 'count' element
$start = array_search( 'registered:current', $array[0], true);
$end = array_search( 'END', $array[0], true); // Change 'END' to whatever it is
$return = array_slice( $array[0], $start + 1, ($end ? ($end - $start - 1) : null));
这个怎么样?
$end = array_search( 'END', $array, true);
$return = array_slice( $array,
array_search( 'START', $array, true) + 1,
($end ? ($end - count( $array)) : null)
);
如果未找到'END'
,array_search()
将返回false,这将导致array_slice()
的第三个参数设置为null
,从而从'START'
开始返回数组中的其余元素。但是,如果找到了'END'
,您将得到一个包含'START'
和'END'
之间元素的数组,如本演示中所示。
编辑:这里有一个更简单的实现,它直接使用索引,它基于Matt的编辑,并进行了一些调整,使其不包括分隔符:
$start = array_search( 'START', $array, true) + 1; // +1 to get rid of 'START'
$end = array_search( 'END', $array, true);
$return = array_slice( $array, $start, ($end ? ($end - $start - 1) : null)); // Omit 3rd param if 'END' is not found
编辑:最终实现:
array_shift( $array[0]); // Get rid of the 'count' element
$start = array_search( 'registered:current', $array[0], true);
$end = array_search( 'END', $array[0], true); // Change 'END' to whatever it is
$return = array_slice( $array[0], $start + 1, ($end ? ($end - $start - 1) : null));
取array_search()
返回的索引。试试这个:
$startIndex = array_search("START", $myArray);
$endIndex = array_search("END", $myArray);
if ($endIndex === false) {
$endIndex = count($myArray) - 1;
}
$newArray = array();
for($i = $startIndex; $i < $endIndex; $i++) {
// do your thing
$newArray[] = $myArray[$i];
}
UPDATE:可以使用array_slice()
来代替循环。
$newArray = array_slice($myArray, $startIndex, $endIndex - $startIndex);
$myArray = array( 'a','b','c','START','d','e','f','END' );
$arr = array();
$start = false;
foreach($myArray as $val) {
if($val == 'END') {
break;
}
if($start) {
$arr[] = $val;
}
if($val == 'START') {
$start = true;
}
}
print_r($arr);
foreach ($myArray as $A){
if(//condition of the elements you want to display){
}
}
如果我们确切地知道您的数组是如何构造的,那么会更容易提供帮助。