请教这样的数组取值

请问以下的数组如何foreach获取 aid,id,sheng这样呢,如:

aid:abc,id:1,sheng:广东

array
(
[0] => array
(
[aid] => abc
)
[1] => array
(
[list] => array
(
[id] => 1
[sheng] => 广东
)
)
[2] => array
(
[aid] => defg
)
[3] => array
(
[list] => array
(
[id] => 11
[sheng] => 上海
)
)
[4] => array
(
[aid] => aaaa
)
[5] => array
(
[list] => array
(
[id] => 111
[sheng] => 北京
)
)
[6] => array
(
[aid] => bbbb
)
[7] => array
(
[list] => array
(
[id] => 1111
[sheng] => 云南
)
)
[8] => array
(
[aid] => cccc
)
[9] => array
(
[list] => array
(
[id] => 121
[sheng] => 香港
)
)
)

回复讨论(解决方案)

$result=array

(

[0] => array

(

[aid] => abc

)

[1] => array

(

[list] => array

(

[id] => 1

[sheng] => 广东

)

)

[2] => array

(

[aid] => defg

)

[3] => array

(

[list] => array

(

[id] => 11

[sheng] => 上海

)

)

[4] => array

(

[aid] => aaaa

)

[5] => array

(

[list] => array

(

[id] => 111

[sheng] => 北京

)

)

[6] => array

(

[aid] => bbbb

)

[7] => array

(

[list] => array

(

[id] => 1111

[sheng] => 云南

)

)

[8] => array

(

[aid] => cccc

)

[9] => array

(

[list] => array

(

[id] => 121

[sheng] => 香港

)

)

);

foreach($result as $key=>$v){

if(is_set($v[‘aid’]){

echo “aid:{$v[‘aid’]}”;

}else{

echo “id:{$v[‘list’][‘id’]} sheng:{$v[‘list’][‘sheng’]}”;

}

}

$a = array (
0 =>
array (
‘aid’ => ‘abc’,
),
1 =>
array (
‘list’ =>
array (
‘id’ => ‘1’,
‘sheng’ => ‘广东’,
),
),
2 =>
array (
‘aid’ => ‘defg’,
),
3 =>
array (
‘list’ =>
array (
‘id’ => ’11’,
‘sheng’ => ‘上海’,
),
),
4 =>
array (
‘aid’ => ‘aaaa’,
),
5 =>
array (
‘list’ =>
array (
‘id’ => ‘111’,
‘sheng’ => ‘北京’,
),
),
6 =>
array (
‘aid’ => ‘bbbb’,
),
7 =>
array (
‘list’ =>
array (
‘id’ => ‘1111’,
‘sheng’ => ‘云南’,
),
),
8 =>
array (
‘aid’ => ‘cccc’,
),
9 =>
array (
‘list’ =>
array (
‘id’ => ‘121’,
‘sheng’ => ‘香港’,
),
),
);
foreach(array_chunk($a, 2) as $v) {
$r[] = array_merge($v[0], current($v[1]));
}
var_export($r);

array (
0 =>
array (
‘aid’ => ‘abc’,
‘id’ => ‘1’,
‘sheng’ => ‘广东’,
),
1 =>
array (
‘aid’ => ‘defg’,
‘id’ => ’11’,
‘sheng’ => ‘上海’,
),
2 =>
array (
‘aid’ => ‘aaaa’,
‘id’ => ‘111’,
‘sheng’ => ‘北京’,
),
3 =>
array (
‘aid’ => ‘bbbb’,
‘id’ => ‘1111’,
‘sheng’ => ‘云南’,
),
4 =>
array (
‘aid’ => ‘cccc’,
‘id’ => ‘121’,
‘sheng’ => ‘香港’,
),
)如果把你的数组改造成这样,就应该会处理了吧?

$result=‘’

foreach($result as $key=>$v){

if(is_set($v[‘aid’]){

echo “aid:{$v[‘aid’]}”;

}else{

echo “id:{$v[‘list’][‘id’]} sheng:{$v[‘list’][‘sheng’]}”;

}

}

运行后parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in,是数组有错误吗?

$a = ”;
)如果把你的数组改造成这样,就应该会处理了吧?

如果是这样的数组当然没问题。

能请教你是如何转换成这样的数组吗?

[0] => array
(
[aid] => abc
)
[1] => array
(
[list] => array
(
[id] => 1
[sheng] => 广东
)
)
这样的转成了这样的
0 =>
array (
‘aid’ => ‘abc’,
),
1 =>
array (
‘list’ =>
array (
‘id’ => ‘1’,
‘sheng’ => ‘广东’,
),
),

if(is_set($v[‘aid’]){

应为

if(isset($v[‘aid’])){

Posted in 未分类

发表评论