[英]PHP Arrays: Loop through array with a lot of conditional statements
I don't know how to get it to work the best way. 我不知道如何使其以最佳方式工作。
I need to loop through an array like the one below. 我需要遍历如下数组。 I need to check if the [country] index is equal to a Spanish speaking country (lot of countries I predefine) and then get those [title] indexes of the correspondent country, check for duplicates and create new more compact and simplified array. 我需要检查[country]索引是否等于说西班牙语的国家(我预先定义的许多国家),然后获取对应国家的那些[title]索引,检查重复项并创建新的更紧凑和简化的数组。
The original array: 原始数组:
Array
(
[0] => Array
(
[title] => Jeux de pouvoir
[country] => France
)
[1] => Array
(
[title] => Los secretos del poder
[country] => Argentina
)
[2] => Array
(
[title] => Los secretos del poder
[country] => Mexico
)
[3] => Array
(
[title] => El poder secreto
[country] => Uruguay
)
)
goes on and on....
To help you understand, the final result I need to get looks something like this: 为了帮助您理解,我需要获得的最终结果如下所示:
Array (
[0] => Array
(
[title] => Los secretos del poder
[country] => Argentina, Mexico
)
[1] => Array
(
[title] => El poder secreto
[country] => Uruguay
)
)
As you can see, when there is the same title for lot of countries the array gets simplified by adding those countries to the same [country] index of the corresponding [title]. 如您所见,当许多国家/地区具有相同的标题时,通过将这些国家/地区添加到相应[title]的相同[country]索引中,可以简化数组。
How would you do it? 你会怎么做?
assuming $spanish_countries is an array of spanish speaking countries... 假设$ spanish_countries是一系列讲西班牙语的国家...
foreach ( $array as $a ) {
if ( in_array($a['country'], $spanish_countries) ) {
$final_array[$a['title']][] = $a['country'];
}
}
this will result in a different array at the end but would be trivial to get to your format 这将导致最后一个不同的数组,但是对于您的格式来说却是微不足道的
foreach ( $final_array as $k => $v ) { $r[] = array( 'title' => $k, 'country' => implode(', ', $v) ); } print_r($r);
youll want better variable names, but this will work 您将需要更好的变量名,但这会起作用
Try with: 尝试:
$input = array( /* your data */ );
$output = $tmp = array();
foreach ( $input as $v ) {
if ( !isset($tmp[$v['title']]) {
$tmp[$v['title']] = array();
}
// here you can check if your counry is spanish speaking
if ( !in_array($v['country'], $spanishSpeakingCountries) ) {
continue;
}
$tmp[$v['title']][] = $v['country'];
}
foreach ( $tmp as $k => $v ) {
$output[] = array(
'title' => $k,
'country' => implode(', ', $v)
);
}
$output; // your output data
foreach($yourarray as $data)
{
$newlist[$data['title']][] = $data['country'];
}
This would give you 这会给你
Array (
['Los secretos del poder'] => Array
(
[0] => Argentina
[1] => Mexico
)
['El poder secreto'] => Array
(
[0] => Uruguay
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.