[英]How to split links of image after GROUP_CONCAT php MySQL
我在兩個表之間創建 GROUP_CONCAT,以使用 LEFT JOIN 收集相似的數據。
這是 GROUP_CONCAT 之前的舊數據:
Output:
+-----------+--------+----------+-----------+
|id| name | Cmpany | POSTID |ImageTopic |
|1 | John | Js | 1 |1png |
|1 | John | Js | 1 |2png |
|1 | John | Js | 1 |3png |
|1 | John | Js | 1 |4png |
+-----------+--------+----------+-----------+
GROUP_CONCAT 的新數據:
Output:
+---+------+-----------+--------+------------------------+
|id | name | Cmpany | POSTID | ImageTopic |
|1 | John | Js | 1 | 1png,2png,3png,4png |
+---+------+-----------+--------+------------------------+
現在我的問題是新數據中的圖像主題列。 我在此專欄中獲得了鏈接圖像,但它沒有精神,所以我無法單擊它或在其他地方使用它。
示例圖像是這樣的:
ImageTopic: "https://png.pngtree.com/element_our/20200703/ourlarge/pngtree-butterfly-purple-red-wings-ink-transparent-png-bright-image_2300442.jpg,https://www.picng.com/upload/butterfly/png_butterfly_61701.png,https://www.picng.com/upload/butterfly/png_butterfly_61701.pnghttps://www.picng.com/upload/butterfly/png_butterfly_61700.png"
正如您在上面看到的,這不是正確的格式。
如果我嘗試點擊它,我會得到這個:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>JF8C24VHE7Z9NKAC</RequestId>
<HostId>+yKClkshmm8kCqYydoRsaPDwjkkM+anF0vQI6nt0eTY6TvCuQ5QDv7hfq//eTxUJ9ApNMNWpPfc=</HostId>
</Error>
我的代碼:
<?php
require_once 'con.php';
$id=$_GET['id'];
$sql= "SELECT * FROM topics
LEFT JOIN (SELECT POSTID, GROUP_CONCAT(DISTINCT ImageTopic ) ImageTopic
FROM ImagePost GROUP BY POSTID
) ImageTopic ON topics.id = ImageTopic.POSTID
where topics.id=? "
;
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
$json = json_encode(["result" => "No Data Foun"]);
}
echo $json;
$con->close();
?>
我該如何解決這個問題?
你可以在這里試試: https://onecompiler.com/mysql/3yhc5dnkh
這 URL 張圖片我稍后也會在我的應用程序中使用它。
如果您進一步處理 PHP 中的數據,您可以使用explode function 將它們分解成一個數組。
$imageTopicArray = explode(',', $imageTopic);
foreach ($imageTopicItem as $imageTopicArray) {
echo '<img src="'. $imageTopicItem .'" />';
}
這給你一個字符串數組,你可以一個一個地打印它們。
另一種選擇是使用自JSON_ARRAYAGG
5.7.22 起可用的 JSON_ARRAYAGG function。 而不是GROUP_CONCAT
。 這將返回 JSON 數組而不是逗號分隔值,這在某些情況下可能更舒服。
然后使用json_decode獲取項目數組並按上述方法處理它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.