且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP单数组多维价值观

更新时间:2023-02-27 09:24:19

试试这个:

<pre><?php

$oldArray = array( 
    array('topCat'=> "1", 'secondCat'=> "1", 'listItem'=> "List Item 1"), 
    array('topCat'=> "1", 'secondCat'=> "1", 'listItem'=> "List Item 2"),
    array('topCat'=> "1", 'secondCat'=> "2", 'listItem'=> "List Item 1"), 
    array('topCat'=> "1", 'secondCat'=> "3", 'listItem'=> "List Item 2"), 
    array('topCat'=> "2", 'secondCat'=> "1", 'listItem'=> "List Item 1"));

var_dump($oldArray);

$newArray =  array();

  $newArray = array();
    foreach ($oldArray as $row){
      $newArray[$row['topCat']][$row['secondCat']][] = $row['listItem'];

    }
var_dump($newArray);

$t2 = array();
foreach($newArray as $index=>$back){
foreach($back as $index2=>$back2){
    $t2[] = array('topCat'=>$index, 'secondCat'=>$index2, 'listItem'=>$back2);
}}
var_dump($t2);

返回:

array(4) {
  [0]=>
  array(3) {
    ["topCat"]=>
    int(1)
    ["secondCat"]=>
    int(1)
    ["listItem"]=>
    array(2) {
      [0]=>
      string(11) "List Item 1"
      [1]=>
      string(11) "List Item 2"
    }
  }
  [1]=>
  array(3) {
    ["topCat"]=>
    int(1)
    ["secondCat"]=>
    int(2)
    ["listItem"]=>
    array(1) {
      [0]=>
      string(11) "List Item 1"
    }
  }
  [2]=>
  array(3) {
    ["topCat"]=>
    int(1)
    ["secondCat"]=>
    int(3)
    ["listItem"]=>
    array(1) {
      [0]=>
      string(11) "List Item 2"
    }
  }
  [3]=>
  array(3) {
    ["topCat"]=>
    int(2)
    ["secondCat"]=>
    int(1)
    ["listItem"]=>
    array(1) {
      [0]=>
      string(11) "List Item 1"
    }
  }
}