-1

我在 foreach 循环中有这个数组

foreach ($data as $key => $value) {
    $filter_cat_name = $this->filter_cat_name($value['filter_cat_id']);
    $filter_sub_cat_name = $this->filter_sub_cat_name($value['sub_cat_id']);
    $var = array($filter_cat_name,$filter_sub_cat_name);
    print_r($var);
}

//foreach output
Array ( [0] => Brand Name [1] => Sony )  
Array ( [0] => Brand Name [1] => nokia )  
Array ( [0] => Display Size [1] => 360 x 640 )  
Array ( [0] => Brand Name [1] => Samsung )  
Array ( [0] => Display Size [1] => 480 x 640 ) 

我怎样才能像这样格式化或更改

品牌名称
索尼
诺基亚
三星

显示尺寸
360 x 640
480 x 640

4

3 回答 3

0

这应该有帮助。

<?php
foreach ($data as $key => $value) {

                $filter_cat_name = $this->filter_cat_name($value['filter_cat_id']);
                $filter_sub_cat_name = $this->filter_sub_cat_name($value['sub_cat_id']);

                $var = array($filter_cat_name,$filter_sub_cat_name);
if($var[0]=='Brand Name')
$brand[] = $var[1]; // For Brand Name

if($var[0]== 'Display Size')
$size[] = $var[1]; // For Display Name       
                print_r($var);

    }
print_r($brand);
print_r($size);
?>
于 2012-11-09T07:58:00.673 回答
0

这会有帮助吗?

foreach ($data as $key => $value) {
    $filter_cat_name = $this->filter_cat_name($value['filter_cat_id']);
    $filter_sub_cat_name = $this->filter_sub_cat_name($value['sub_cat_id']);

    if (!isset($var[$filter_cat_name])) {
         $var[$filter_cat_name] = array();
    }
    $var[$filter_cat_name][] = $filter_sub_cat_name;
}

$brands = $var['Brand Name'];
$displays = $var['Displays'];

这将格式化您的$var喜欢

Array(
    ['Brand Name'] => array('Nokia','Samsung'),
    ['Displays']   => array('320x120','140x70')
)
于 2012-11-09T07:47:41.600 回答
0

这应该可以帮助您:

$i=0;
$groups = array();
foreach($array as $item){
   $groups[$item[0]][$i] = $item[1];
   $i++;
}

输出:

array 
'BrandName' =>  
  array
  0 => string 'Sony' (length=4) 
  1 => string 'nokia' (length=5) 
  3 => string 'Samsung' (length=7) 
'Display Size' =>
  array 
  2 => string '360 x 640' (length=9) 
  4 => string '480 x 640' (length=9)
于 2012-11-09T08:49:14.903 回答