我的嵌套数组如下:
array (
0 =>
array (
'id' => 1,
'category_name' => 'Vehicle',
0 =>
array (
'id' => 4,
'category_name' => 'Bmw',
0 =>
array (
'id' => 5,
'category_name' => 'Mercedes',
0 =>
array (
'id' => 6,
'category_name' => 'Bmw X7',
),
),
),
),
1 =>
array (
'id' => 2,
'category_name' => 'TV',
0 =>
array (
'id' => 8,
'category_name' => 'Led TV',
0 =>
array (
'id' => 9,
'category_name' => 'Philips',
),
),
),
2 =>
array (
'id' => 3,
'category_name' => 'Phone',
0 =>
array (
'id' => 10,
'category_name' => 'Samsung',
),
),
)
我的代码如下:
public function index($id) { $categories= array( array('id' => 1 , 'category_name' => 'Vehicle', array('id' => 4 , 'category_name' => 'Bmw',array('id' => 5 , 'category_name' => 'Mercedes' , array('id' => 6 , 'category_name' => 'Bmw X7')))), array('id' => 2 , 'category_name' => 'TV', array('id' => 8 , 'category_name' => 'Led TV' , array('id' => 9 , 'category_name' => 'Philips'))), array('id' => 3 , 'category_name' => 'Phone' , array('id' => 10 , 'category_name' => 'Samsung')) ); foreach ($categories as $row) { if($row['id'] == $id) { $parent_category = $row; break; } } }
我可以达到第一个数组ID值。我想在里面得到id值。我期待你的帮助,非常感谢你。
答案 0 :(得分:0)
不知何故,我想出了你想要的东西,你需要在第一个循环中有另一个foreach
循环:
foreach ($categories as $row) {
echo $row["id"];
foreach ($row as $key => $value) {
echo $value["id"];
}
}
答案 1 :(得分:0)
解决问题如下:
$result = array();
$search = 'id';
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(
$categories,
RecursiveArrayIterator::CHILD_ARRAYS_ONLY
)
);
foreach($iterator as $key=>$value)
{
if($search==$key && $value!=='')
{
if($value == 10){
$result[] = array($key => $value);
break;
}
}
}