我有以下数组$myarr
和$ url值:
$url = "http://www.example.com/jane-doe/testingideas.html";
stdClass Object
(
[items] => Array
(
[0] => stdClass Object
(
[updated] => 2015-01-08 17:22:23.279210
[url] => http://www.example.com/jane-doe/testingideas.html
[score] => 21.053322
)
[1] => stdClass Object
(
[updated] => 2015-01-08 17:22:23.279226
[url] => http://www.example.com/john-doe/ideas.html
[score] => 18.889984
)
)
)
该数组有超过2000个值。我复制了2来简化事情。我需要根据URL检索分数。这是我写的代码:
$myarr = $output->items;
foreach ($myarr as $val){
if ($val->url == $url ) {
$score = round($val->score);
} else $score = 'N/A';
}
这不起作用,因为即使URL匹配也找不到任何分数。
我还修剪了两个网址以删除任何空格,但我遇到了同样的问题。
答案 0 :(得分:1)
您在每个循环中取消设置$score
,您最好这样做:
$myarr = $output->items;
$score = 'N/A';
foreach ($myarr as $val){
if ($val->url == $url ) {
$score = round($val->score);
}
}
答案 1 :(得分:0)
这应该适合你:
foreach ($myarr as $items) {
foreach($items as $item) {
if ($item->url == $url ) {
$score = round($val->score);
} else {
$score = 'N/A';
}
}
}
答案 2 :(得分:0)
$url = "http://www.example.com/jane-doe/testingideas.html";
$myarr = $output->items;
foreach ($myarr as $val){
if (strcmp($val->url,$url) == 0) {
$score = round($val->score);
} else {
$score = 'N/A';
}
}
答案 3 :(得分:0)
尝试使用trim()
确保没有过多的空格:
if (trim($item->url) == trim($url))