我有一个这样的字符串: -
$sa_position = "state/Gold,International/Participant,School/Participant,School/Bronze,national/Bronze,School/Gold";
我希望以某种方式过滤此字符串以获得前三名奖品并按奖品排序(例如州/金,州/金,国家/铜奖)
答案 0 :(得分:1)
爆炸功能上没有分隔符。
explode ( string $delimiter , string $string [, int $limit ] )
答案 1 :(得分:0)
多田!这是你的排序。简单但优雅:)
<?php
$sa_position = explode(",", "state/Gold,International/Participant,School/Participant,School/Bronze,national/Bronze,School/Gold");
//$new = sortMedals($sa_position, array('Gold', 'Silver', 'Bronze', 'Participant'));
$gold = array();
$silver = array();
$bronze = array();
$participated = array();
foreach($sa_position as $item)
{
if(stripos($item, "silver"))
$silver[] = $item;
else if(stripos($item, "bronze"))
$silver[] = $item;
else if(stripos($item, "gold"))
$gold[] = $item;
else if(stripos($item, "participant"))
$participated[] = $item;
}
$new = array_merge($gold, $silver, $bronze, $participated);
print_r($new);
?>
答案 2 :(得分:0)
您的代码中存在很多问题。这是你应该做的:
explode
需要分隔符。您想用逗号分隔它,explode(",","state/Gold,International/Participant,School/Participant,School/Bronze,national/Bronze,School/Gold")
。你需要的是一个名为array_filter
的漂亮功能。这是PHP中为数不多的非常棒的东西之一,所以请耐心等一下我解释它是如何工作的。
它有两个参数:数组和函数。
它返回一个只包含元素的数组,这些元素一旦传递给函数,就会返回true。
让我们回到你的具体案例。要检查字符串是否包含子字符串(即,要检查给定数组元素中是否存在“Participant”字符串),可以使用strpos($haystack, $needle)
。它将返回substr的位置,如果不存在则返回FALSE。
我们将使用的另一个概念(解决方案即将推出)在php中很新,被称为“匿名函数”。它是一个动态创建的函数,没有名称,通常用作回调。
以下是代码:
$string = "state/Gold,International/Participant,School/Participant,School/Bronze,national/Bronze,School/Gold";
$new_array = array_filter(
explode(",",$string), //so, every element of this array gets checked against
function ($var) { //this function here. if true is returned, it goes in $new_array
return (strpos($haystack, 'Participant')=== NULL);
}
);