我正在使用多維php數組來提供html代的數據,並且當我的兩個子數組(包含不同的鍵)包含相同的值時,我注意到了一些奇怪的行爲。例如,該陣列產生重複:PHP foreach複製具有相同內容的子陣列
$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變量 –