我正在通過創建一家服裝店來練習php。PHP - 搜索多維數組中的值並返回其ID
考慮我的PHP數據庫陣列:
$mens[101] = [
"title" => "Block Original T-Shirt",
"img" => "img/clothing/men/tShirts/block-orig-black.jpg",
"price" => 16,
"color" => "black",
"altColor" => array("black" , "white", "grey"),
"size" => array (
array(
"size" => "x-small",
"qty" => 3
),
array(
"size" => "small",
"qty" => 10
),
array(
"size" => "medium",
"qty" => 0
),
array(
"size" => "large",
"qty" => 15
),
array(
"size" => "x-large",
"qty" => 9
)
),
"description" => "Duis eget volutpat mauris, quis lacinia orci. Cras mattis bibendum lorem, nec faucibus ipsum fermentum at. Nulla tincidunt ligula suscipit elit tincidunt, non vulputate nibh dapibus. Proin quis sapien hendrerit, vulputate nibh sit amet, rutrum quam.",
"category" => "m-tShirts"
];
$mens[102] = [ ....]
$mens[103] = [ ....]
$mens[...
一個新手的問題,理所當然的,但我循環通過數據庫尋找與類別=「M恤」這些項目,一旦我發現這些我會喜歡從這些結果中挑選一個隨機項目來處理。
foreach($mens as $sug) {
if ($sug["category"] === "m-shirts") {
echo key($mens);
}
}
我使用的回聲,以檢查是否正在收集正確的ID。然而,這回聲「101」15倍(產品的數量類別「米衫」)。但我想要這些特定結果的唯一ID(巧合的是ID爲201到215)。英語我想:
foreach(product in $mens array){
if(product has the category "m-shirts"){
collect the id's;
select a random id and store as variable $suggestion
}
}
如果有人可以幫助我,或指向我任何文章/教程的方向。我花了大部分時間閱讀了php文檔,並且還通過學習PHP,MySQL和JavaSript(由Robin Nixon編寫)關於數組的章節,但無法解決這個問題。
謝謝提前!
哪裏這些ID是? –
當使用[的foreach(http://php.net/manual/en/control-structures.foreach.php),可以指定一個變量來保存當前'key',像這樣:'的foreach($陣列$ key => $ value)' – FirstOne
你發佈的數組的ID在哪裏?這些ID是陣列的關鍵?那是;是陣列$男士[** 101 **]的ID = ** 101 **?因爲整個陣列中沒有ID Key。 – Poiz