我从数据库中获取了这种类型的数组:(我无法更改收到的数据类型,因为它来自外部源)
Array
(
[0] => Es\Result Object
(
[_hit:protected] => Array
(
[_index] => website
[_type] => structure
[_id] => 8
[_score] => 0.625
[_source] => Array
(
[name] => Test1
[locality] => Array
(
[locality] => Bologna
[sign] => BO
[province] => Array
(
[province] => Bologna
[region] => Array
(
[region] => Emilia Romagna
)
)
)
)
)
)
[1] => Elastica\Result Object
(
[_hit:protected] => Array
(
[_index] => website
[_type] => structure
[_id] => 6
[_score] => 0.625
[_source] => Array
(
[name] => Test2
[locality] => Array
(
[locality] => Bologna
[sign] => BO
[province] => Array
(
[province] => Bologna
[region] => Array
(
[region] => Emilia Romagna
)
)
)
)
)
)
......
我输入一个json对象值“locality”并计算有多少“locality”相等,例如:
foreach ($results as $result) {
$source = $result->getSource();
$locality = $source['locality']['locality'];
$dataLocality[] = array(
'type' => 'locality',
'label' => $locality,
'count' => 1, //How to increase the count here?
);
}
我试图把所有东西都放在一个循环中,但我无法正确计算这些值。
有办法做到这一点吗?
修改
这应该是我得到的结果:
让我说我得到的阵列有3个“地点”:
2“foo”
1“bar”
$dataLocality =
Array
(
[0] => Array
(
[type] => 'locality'
[locality] => 'foo'
[count] => 2
)
[1] => Array
(
[type] => 'locality'
[locality] => 'bar'
[count] => 1
)
)
答案 0 :(得分:0)
$ locality的值是否存在于数组中?如果不是,则将其存储为1.如果是,则将1添加到计数中。
foreach ($results as $result) {
$source = $result->getSource();
$locality = $source['locality']['locality'];
// Manually specify the array key. This makes life much easier down the road,
// especially when you need to find items in the array.
if ( !isset($dataLocality[$locality]) ) {
$dataLocality[$locality] = array('type' => 'locality',
'label' => $locality,
'count' => 1);
} else {
$dataLocality[$locality]['count'] += 1;
}
}
答案 1 :(得分:0)
在foreach循环之外声明一个数组(比如$dataLocality
)。在每个循环中,您在$datalocality
中搜索一个存在的位置(如果$result
在$dataLocality
中)。如果有,则将计数器递增$dataLocality[$indexOfFounding]['count']++
。
如果您在$ dataLocality中找不到任何位置,则此课程需要添加“type”,“label”和“count”数组。
在foreach循环之后,您可以浏览阵列并输出或对结果执行任何操作。
答案 2 :(得分:0)
如果您需要地点数组,请使用count
尝试:
foreach ($results as $result) {
$source = $result->getSource();
$locality = $source['locality']['locality'];
$dataLocality[] = array(
'type' => 'locality',
'label' => $locality,
'count' => count($source['locality']), //get locality array count
);
}
答案 3 :(得分:0)
感谢@ Dave的回复我解决了这个问题,但由于我没有命名密钥,我在循环外添加了:
$dataLocality = array_values($dataLocality);
所以解决问题的完整代码,但有时候有人遇到类似我的问题是:
foreach ($results as $result) {
$source = $result->getSource();
if(!isset($dataLocality[$locality = $source['locality']['locality']])) {
$dataLocality[$locality] = array(
'type' => 'locality',
'label' => $locality,
'count' => 1,
);
} else {
$dataLocality[$locality]['count']++;
}
}
$dataLocality = array_values($dataLocality);