如何在foreach循环中逐字拆分数组

时间:2015-07-10 08:26:55

标签: php arrays

我有以下数组:

$phones = array(
  [0] => Apple iPhone 4
  [1] => Apple iPhone 5
  [2] => Samsung Galaxy S6
)

我想要做的就是拆分这个阵列,将品牌与手机型号分开,所以最后我可以建立一个阵列来给我这个:

$phone_array = array (
  'Apple' => array (
      'iPhone 4', 'iPhone 5'
  ),
  'Samsung' => array (
      'Galaxy S6',
  )
)

到目前为止,我有以下未完成的代码:

        $brand_dictionary = "/(samsung|apple|htc|sony|nokia)/i";
        foreach($phones as $p) {
            if(stripos($p,$brand_dictionary)) {
                pr($p);
                die();
            }
        }

但这根本不能正常工作。

2 个答案:

答案 0 :(得分:3)

尝试 -

$phones = array(
  'Apple iPhone 4',
  'Apple iPhone 5',
  'Samsung Galaxy S6'
);

$new = array();

foreach($phones as $phone) {
  $temp = explode(' ', $phone);
  $key = array_shift($temp);
  $new[$key][] = implode(' ', $temp); 
}

var_dump($new);

<强>输出

array(2) {
  ["Apple"]=>
  array(2) {
    [0]=>
    string(8) "iPhone 4"
    [1]=>
    string(8) "iPhone 5"
  }
  ["Samsung"]=>
  array(1) {
    [0]=>
    string(9) "Galaxy S6"
  }
}

答案 1 :(得分:2)

可能更简单,

$phones = ['Apple iPhone 4','Apple iPhone 5','Samsung Galaxy S6'];

$final = [];

foreach($phones as $phone)
{
    $brand_name = strtok($phone, " ");
    $final[$brand_name][] = trim(strstr($phone, " "));
}

转储$final

array (size=2)
  'Apple' => 
    array (size=2)
      0 => string 'iPhone 4' (length=8)
      1 => string 'iPhone 5' (length=8)
  'Samsung' => 
    array (size=1)
      0 => string 'Galaxy S6' (length=9)