欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PHP foreach数组循环

程序员文章站 2022-01-18 10:06:12
...

数组的数据

  1. $arr=[
  2. [
  3. 'area_id' => 110000,
  4. 'area_pid' => 0,
  5. 'area_name' => '北京',
  6. 'lng' => 116.405,
  7. 'lat' => 39.905,
  8. 'son' => [
  9. [
  10. 'area_id' => 110100,
  11. 'area_pid' => 110000,
  12. 'area_name' => '北京市',
  13. 'lng' => 116.405,
  14. 'lat' => 39.905,
  15. 'son' => [
  16. [
  17. 'area_id' => 110101,
  18. 'area_pid' => 110100,
  19. 'area_name' => '东城区',
  20. 'lng' => 116.41,
  21. 'lat' => 39.9316
  22. ],
  23. [
  24. 'area_id' => 110102,
  25. 'area_pid' => 110100,
  26. 'area_name' => '西城区',
  27. 'lng' => 116.36,
  28. 'lat' => 39.9305
  29. ]
  30. ]
  31. ]
  32. ]
  33. ],
  34. [
  35. 'area_id' => 120000,
  36. 'area_pid' => 0,
  37. 'area_name' => '天津',
  38. 'lng' => 117.19,
  39. 'lat' => 39.1256,
  40. 'son' => [
  41. [
  42. 'area_id' => 120100,
  43. 'area_pid' => 120000,
  44. 'area_name' => '天津市',
  45. 'lng' => 117.19,
  46. 'lat' => 39.1256,
  47. 'son' => [
  48. [
  49. 'area_id' => 120101,
  50. 'area_pid' => 120100,
  51. 'area_name' => '和平区',
  52. 'lng' => 117.215,
  53. 'lat' => 39.1172
  54. ],
  55. [
  56. 'area_id' => 120102,
  57. 'area_pid' => 120100,
  58. 'area_name' => '河东区',
  59. 'lng' => 117.226,
  60. 'lat' => 39.1232
  61. ]
  62. ]
  63. ]
  64. ]
  65. ]
  66. ];
输出单个数据
  1. print_r($arr[0]['son'][0]['area_name']); //输出北京市

循环出的数据

  1. foreach ($arr as $v) {
  2. echo '<ul>';
  3. echo '<li>'.$v['area_id'].'-'.$v['area_pid'].'-'.$v['area_name'].'-'.$v['lng'].'-'.$v['lat'].'</li>';
  4. foreach ($v['son'] as $v2) {
  5. echo '<ul><li>'.$v2['area_id'].'-'.$v2['area_pid'].'-'.$v2['area_name'].'-'.$v2['lng'].'-'.$v2['lat'].'</li></ul>';
  6. foreach ($v2['son'] as $v3) {
  7. echo '<ul><ul><li>'.$v3['area_id'].'-'.$v3['area_pid'].'-'.$v3['area_name'].'-'.$v3['lng'].'-'.$v3['lat'].'</li></ul></ul>';
  8. }
  9. }
  10. echo '</ul>';
  11. echo '<hr>';
  12. }
输出效果

PHP foreach数组循环