我有一个这样的字符串:-
$sa_position = "state/Gold,International/Participant,School/Participant,School/Bronze,national/Bronze,School/Gold";我想以某种方式过滤这个字符串,以获得前3个奖品并按奖品排序(例如,州/金牌,州/金牌,国家/铜牌)
发布于 2011-04-09 13:54:43
你的代码中有相当多的问题。下面是你应该做的:
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);
}
);https://stackoverflow.com/questions/5603130
复制相似问题