开发者

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.

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].

How would you do it?


assuming $spanish_countries is an array of spanish speaking 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


Edit for comment

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
        ) 
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜