PHP:如何根据IF / ELSE STATEMENT在主ARRAY()中创建单独的ARRAY()?

时间:2015-11-16 07:53:32

标签: php arrays

Good Day Guys,我在php中的 array()中遇到了问题。我在 $ continents $ countrie 下面有(2)$ _POST数组。当系统找到('asia','europe','america')时,我使用 array_combined 执行 IF / ELSE STATEMENT 我想为每个大陆创建新的 array(),我不能使用 array_slice(),因为数组值取决于用户选择。它是否正确?以下示例。

$continents = array('europe','europe', 'asia', 'asia','america','america');
$countries = array('england','spain', 'iraq', 'china','chile','argentina');

$result = array_combine($countries,$continents);

// It this correct?       
if($result == 'asia'){

 // this is I want to execute. To create a new array   
 print_r( array('iraq','china') ); 

}else if($result == 'europe'){

  // this is I want to execute.To create a new array   
  print_r( array('england','spain') ); 

}else if($result == 'america'){

  // this is I want to execute. To create a new array  
  print_r( array('chile','argentina') ); 

}

谢谢大家!

2 个答案:

答案 0 :(得分:0)

这个怎么样?

$continents = array(
    '0' => 'europe', 
    '1' => 'europe', 
    '2' => 'asia', 
    '3' => 'asia', 
    '4' => 'america', 
    '5' => 'america'
    );

$countries = array(
    '0' => 'england', 
    '1' => 'spain', 
    '2' => 'iraq', 
    '3' => 'china', 
    '4' => 'chile', 
    '5' => 'argentina'
    );

$result = array_combine($countries,$continents);


print_r($result);

// It this correct?       
if($result == 'asia'){

    $new_cont[] = array(
        '0' =>  'iraq',
        '1' =>  'china'
        );

 // this is I want to execute. To create a new array   
    print_r($new_cont); 

}else if($result == 'europe'){

    $new_cont[] = array(
        '0' =>  'england',
        '1' =>  'spain'
        );

 // this is I want to execute. To create a new array   
    print_r($new_cont); 

}else if($result == 'america'){

    $new_cont[] = array(
        '0' =>  'chile',
        '1' =>  'argentina'
        );

 // this is I want to execute. To create a new array   
    print_r($new_cont);

}

阅读本文

  1. array_combine()
  2. array_merge()
  3. array_diff()

答案 1 :(得分:0)

你只需要一个循环:

$continents = array('europe', 'europe', 'asia', 'asia', 'america', 'america');
$countries = array('england', 'spain', 'iraq', 'china', 'chile', 'argentina');

echo '<br/>Original Array:<pre>';
print_r(array_combine($countries, $continents));
$cochinada = array_combine($countries, $continents);
echo '</pre><br />';

foreach($cochinada as $key => $value){
    $array2[$value][] = $key;
}

echo '<br/>Final Array:<pre>';
print_r($array2);
echo '</pre>'

输出是:

Original Array:
Array(
[england] => europe
[spain] => europe
[iraq] => asia
[china] => asia
[chile] => america
[argentina] => america
)

Final Array:
Array(
[europe] => Array(
        [0] => england
        [1] => spain
    )
[asia] => Array(
        [0] => iraq
        [1] => china
    )
[america] => Array(
        [0] => chile
        [1] => argentina
    )
)