dongque6377 2015-02-26 06:19
浏览 19
已采纳

PHP通过多维数组循环

Hi I have this multi dimensional array in PHP:

$team_arrays = array (
                        "lakers" => array (
                                        24 => "Bryant",
                                        6  => "Price",
                                        17 => "Lin"
                        ),

                        "knicks" => array (
                                        7 => "Anthony",
                                       22 => "Shumpert",
                                       12 => "Jackson"
                        ),

                        "thunder" => array (
                                       35 => "Durant",
                                       0  => "Westbrook",
                                       13 => "Miller"
                        )
                    );

I wanted to display something like this:

Team Name: lakers

  1. Bryant = 24
  2. Price = 6
  3. Lin = 17

Team Name: knicks

  1. Anthony = 7
  2. Shumpert = 22
  3. Jackson = 12

...

This is the code that I tried but seems not to work:

foreach ($team_arrays as $names => $team) {
                        echo "<h2>Team Name: " . $names . "</h2>";
                        echo "<ol>";
                            foreach ($team_arrays as $jersey => $names) {
                                echo "<li>" . $names . " = " . $jersey . "</li>";
                            }
                        echo "</ol>";
                    }

It generates this kind of error

Notice: Array to string conversion in

Would anyone tries for a help. Please.

I found this solution from other question but seems I can't relate to it.

  • 写回答

3条回答 默认 最新

  • douzong5057 2015-02-26 06:21
    关注

    There is only one small problem in your code

    foreach ($team_arrays as $jersey => $names) {
             ^ // again looping over the same outer array?
    

    That inner loop is wrong, you should loop over $team and not $team_arrays because your outer loop picks up each team using $team variable.

    foreach ($team as $jersey => $names) {
    

    Rest of your code and logic is already fine.

    Fiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源