从 mysql 问题中重新编号行号

我怎样才能直接在 mysql 问题中或在 php 中使输出看起来像这样?标记 Angelas tips_number 3 在表中丢失,我想在输出中将其重新编号为 1-3。此外,只有具有多个 tips_number 的 ID 才应在其名称后加上数字。


George Danton

Herbert G Wells (1)

Herbert G Wells (2)

Angela (1)

Angela (2)

Angela (3)


+--------+------------------+--------------+

| id     | name             | tips_number  |

+--------+------------------+--------------+

|      1 | Georges Danton   |      1       |

|      2 | Herbert G Wells  |      1       |

|      2 | Herbert G Wells  |      2       |

|      3 | Angela           |      1       |

|      3 | Angela           |      2       |

|      3 | Angela           |      4       |

+--------+------------------+--------------+

我得到的最接近的是这个


foreach($id as $row)

    {

    if($row['tips_number'] > 1){

    $tip_number = $row['tips_number'];

    $name = $row['name']; 

    $result = "{$name} ($tip_number)";

    }

    else $result = $row["name"];       

    echo "$result <br>";

    }

哪个得到输出


George Danton

Herbert G Wells 

Herbert G Wells (2)

Angela 

Angela (2)

Angela (4)


眼眸繁星
浏览 75回答 1
1回答

MM们

在进行输出之前,您需要知道有多个条目,以确保它们都得到正确的显示。这用于array_count_values()计算每个名称的条目数。然后它遍历这些名字——用另一个循环输出这个名字出现的次数。$tips = array_count_values(array_column($id, "name"));foreach ( $tips as $name => $tipCount )&nbsp; &nbsp;{&nbsp; &nbsp; for ( $i = 1; $i <= $tipCount; $i++ )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo $name;&nbsp; &nbsp; &nbsp; &nbsp; if ( $tipCount > 1 )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "($i)";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo "<br>";&nbsp; &nbsp; }}这会将每个人的所有输出捆绑在一起,因此如果元素通过输入传播,那么您将需要一种稍微不同的方法。
打开App,查看更多内容
随时随地看视频慕课网APP