php数组查找和格式化数组

时间:2012-11-09 07:43:23

标签: php

我在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

3 个答案:

答案 0 :(得分: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')
)

答案 1 :(得分: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);
?>

答案 2 :(得分: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)