我是如何正确创建这个PHP数组的?

时间:2017-01-26 06:53:07

标签: php arrays multidimensional-array

我正在使用如下的PHP数组:

$categories = array(
    array('id' => 1,  'parent' => 0, 'name' => 'Category A'),
    array('id' => 2,  'parent' => 0, 'name' => 'Category B'),
    array('id' => 3,  'parent' => 0, 'name' => 'Category C'),
    array('id' => 4,  'parent' => 0, 'name' => 'Category D'),
    array('id' => 5,  'parent' => 0, 'name' => 'Category E'),
    array('id' => 6,  'parent' => 2, 'name' => 'Subcategory F'),
    array('id' => 7,  'parent' => 2, 'name' => 'Subcategory G'),
    array('id' => 8,  'parent' => 3, 'name' => 'Subcategory H'),
    array('id' => 9,  'parent' => 4, 'name' => 'Subcategory I'),
    array('id' => 10, 'parent' => 9, 'name' => 'Subcategory J'),
);

当循环上面的数组时,我想在foreach中创建另一个数组。 那个数组应该是这样的:

$cats[$parent][$id] = $name; 

这是我试过的方式。

  foreach ($categories as $key => $value) {        
    // echo '<pre>', print_r($value). '</pre>';
    // echo $value['id'];
    $cats[$value['parent']][$value['id']] = $value['name'];   
  }

但它不适合我。不工作意味着,它创建了错误的数组。

任何人都可以帮助我。谢谢。

2 个答案:

答案 0 :(得分:0)

喜欢这个。制作类别数组。

<?php

$categories = array(
    array('id' => 1,  'parent' => 0, 'name' => 'Category A'),
    array('id' => 2,  'parent' => 0, 'name' => 'Category B'),
    array('id' => 3,  'parent' => 0, 'name' => 'Category C'),
    array('id' => 4,  'parent' => 0, 'name' => 'Category D'),
    array('id' => 5,  'parent' => 0, 'name' => 'Category E'),
    array('id' => 6,  'parent' => 2, 'name' => 'Subcategory F'),
    array('id' => 7,  'parent' => 2, 'name' => 'Subcategory G'),
    array('id' => 8,  'parent' => 3, 'name' => 'Subcategory H'),
    array('id' => 9,  'parent' => 4, 'name' => 'Subcategory I'),
    array('id' => 10, 'parent' => 9, 'name' => 'Subcategory J'),
);

 foreach ($categories as $key => $value) {        

    $cats[$value['parent']][$value['id']][]= $value['name'];   
  }

  print_r($cats);

答案 1 :(得分:0)

你想要这样

<?php
$categories = array(
array('id' => 1,  'parent' => 0, 'name' => 'Category A'),
array('id' => 2,  'parent' => 0, 'name' => 'Category B'),
array('id' => 3,  'parent' => 0, 'name' => 'Category C'),
array('id' => 4,  'parent' => 0, 'name' => 'Category D'),
array('id' => 5,  'parent' => 0, 'name' => 'Category E'),
array('id' => 6,  'parent' => 2, 'name' => 'Subcategory F'),
array('id' => 7,  'parent' => 2, 'name' => 'Subcategory G'),
array('id' => 8,  'parent' => 3, 'name' => 'Subcategory H'),
array('id' => 9,  'parent' => 4, 'name' => 'Subcategory I'),
array('id' => 10, 'parent' => 9, 'name' => 'Subcategory J'),
);
$newarray = array();
foreach($categories as $array)
{
  $newarray[$array['parent']][$array['id']] = $array['name'];
}
print_r($newarray);