一些简单的代码,如果我有一个json数据的话。我想做一些事情,首先检查json数据中的match string,如果有,输出匹配线之后的值,否则输出所有的json数据。
Exapmle 1,匹配字符串为9,匹配json数据,输出匹配行7,3之后的值。
$txt = '[{"a":"5"},{"a":"9"},{"a":"7"},{"a":"3"}]';
$array = json_decode($txt);
$match_string = '9';
foreach ($array as $data){
echo $data->a;//7, 3
}示例2,匹配字符串为2,在json数据中不匹配,输出所有值5,9,7,3。
$txt = '[{"a":"5"},{"a":"9"},{"a":"7"},{"a":"3"}]';
$array = json_decode($txt);
$match_string = '2';
foreach ($array as $data){
echo $data->a;//5, 9, 7, 3
}该如何判断呢?我在foreach中做了一些类似的事情,只是忽略匹配字符串:
if($match_string == $data->a){
continue;//fut this in the foreach ,get 5, 7, 3, but I need 7, 3, next value from 9.
}谢谢。
发布于 2012-08-22 22:15:08
您需要设置一个标志,告诉您是否找到了匹配项:
$txt = '[{"a":"5"},{"a":"9"},{"a":"7"},{"a":"3"}]';
$array = json_decode($txt);
$match_string = "2";
$found = false;
foreach ($array as $data) {
if ($found) {
echo $data->a;
} else if ($data->a === $match_string) {
// If we set $found *after* we have the opportunity to display it,
// we'll have to wait until the next pass.
$found = true;
}
}
if (!$found) {
// Display everything
foreach ($array as $data) {
echo $data->a;
}
}发布于 2012-08-22 22:34:45
让它变得更短。
$txt = '[{"a":"5"},{"a":"9"},{"a":"7"},{"a":"3"}]';
$array = json_decode($txt);
$toFind = "9";
$mapped = array_map("current",$array);
if (!in_array($toFind,$mapped))
echo implode(", ",$mapped);
else
echo implode(", ",array_slice($mapped,array_search($toFind,$mapped)+1));请注意,您不会使用该函数保留键
为性能而编辑
发布于 2012-08-22 22:13:54
$matched = false;
foreach($array as $data){
if($matched)
echo $data->a;
$matched = ($data->a==$matchString) || $matched;
}
if(!$matched)
foreach($array as $data)
echo $data->a;这是你的基本情况。
https://stackoverflow.com/questions/12074964
复制相似问题