【发布时间】:2017-06-12 06:37:15
【问题描述】:
我正在使用多维 php 数组为 html 生成提供数据,当我的两个子数组(具有不同的键)包含相同的值时,我注意到一些奇怪的行为。例如,这个数组产生重复:
$tableArray = Array(
'rome' => Array(
0 => Array(
'home_prefix' => 'AWE',
'home_number' => '122',
'home_title' => 'Beginning Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to stuff'
)
),
'istanbul' => Array(
0 => Array(
'home_prefix' => 'RPED',
'home_number' => '103',
'home_title' => 'Beginning Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to Greek concepts of stretchiness'
),
1 => Array(
'home_prefix' => 'RPED',
'home_number' => '104',
'home_title' => 'Theory of Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to concepts of stretchiness'
)
),
'new york' => Array(
0 => Array(
'home_prefix' => 'RPED',
'home_number' => '103',
'home_title' => 'Beginning Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to Greek concepts of stretchiness'
),
1 => Array(
'home_prefix' => 'RPED',
'home_number' => '104',
'home_title' => 'Theory of Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to concepts of stretchiness'
)
)
);
foreach ($tableArray as $locationTab):
echo '<p>' . array_search($locationTab, $tableArray) . '</p>';
endforeach;
输出:
罗马
伊斯坦布尔
伊斯坦布尔
但是当我添加另一个子数组时,最后两个数组不相同,没有重复:
$tableArray = Array(
'rome' => Array(
0 => Array(
'home_prefix' => 'AWE',
'home_number' => '122',
'home_title' => 'Beginning Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to stuff'
)
),
'istanbul' => Array(
0 => Array(
'home_prefix' => 'RPED',
'home_number' => '103',
'home_title' => 'Beginning Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to Greek concepts of stretchiness'
),
1 => Array(
'home_prefix' => 'RPED',
'home_number' => '104',
'home_title' => 'Theory of Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to concepts of stretchiness'
)
),
'new york' => Array(
0 => Array(
'home_prefix' => 'RPED',
'home_number' => '103',
'home_title' => 'Beginning Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to Greek concepts of stretchiness'
),
1 => Array(
'home_prefix' => 'RPED',
'home_number' => '104',
'home_title' => 'Theory of Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to concepts of stretchiness'
),
2 => Array(
'home_prefix' => 'RPED',
'home_number' => '104',
'home_title' => 'Theory of Stretching',
'abroad_prefix' => 'ARCH',
'abroad_number' => '111',
'abroad_title' => 'Intro to concepts of stretchiness'
)
)
);
输出:
罗马
伊斯坦布尔
纽约
我该如何解决这个问题,以便 foreach 不会复制子数组?虽然我的二级键是唯一的,但可能存在两个或多个二级键中的值的情况级别数组是相同的。
【问题讨论】:
-
我已经编辑了我的答案。我忘记使用新创建的
$key变量
标签: php arrays multidimensional-array foreach