PHP:CURL结果到数组。 在数组中的A-Z值之后停止,忽略后面的内容
问题描述:
After CURL'ing a page and creating a list of items in an array. I have no control over the markup. I'm trying to filter out the last remainder of items that don't follow the alphabet after the letter Z.
In this case I'd like to disregard indexes 7 and beyond.
Array
(
[0] => Apple
[1] => Acorn
[2] => Banana
[3] => Cucumber
[4] => Date
[5] => Zombify
[6] => Zoo // last item
[7] => Umbrella // disregard
[8] => Kangaroo // disregard
[9] => Apple // disregard
[10] => Star // disregard
[11] => Umbrella // disregard
[12] => Kangaroo // disregard
[13] => Apple // disregard
)
What I cannot figure out is the appropriate solution for the cutoff point at the letter Z.
$letters = range('A', 'Z');
foreach($listContent as $listItem) {
foreach($letters as $letter) {
if (substr($listItem, 0, 1) == $letter) {
$newArray[] = $listItem;
}
}
}
答
This will handle the updated array you posted. For instance, it will keep Zombie and Zoo, but then it will end.
$letters = range('A', 'Z');
$newArray = array();
foreach ($listContent as $listItem) {
$firstLetter = substr($listItem, 0, 1);
if (!in_array($firstLetter, $letters)) {
break; // edited to break instead of continue.
}
$position = array_search($firstLetter, $letters);
$letters = array_slice($letters, $position);
$newArray[] = $listItem;
}
答
How about this:
$last= "A";
foreach($listContent as $listItem) {
$current = strtoupper(substr($listItem, 0,1));
// only add the element if it is alphabetically sorted behind the last element and is a character
if ($current < $last || $current < 'A' || $current > 'Z') break;
$last = $current;
$newArray[] = $listItem;
}
答
Have tested this and works correctly - to my understanding of your requirement:
$letters = range('A', 'Z');
$item_prev_char = "";
foreach( $listContent as $listItem )
{
$item_first_char = substr($listItem, 0, 1);
if ( $item_prev_char <= $item_first_char )
{
foreach( $letters as $letter )
{
if ($item_first_char == $letter )
{
$new_array[] = $listItem;
$item_prev_char = $item_first_char;
echo $listItem."<br/>";
break;
}
}
}
}