2017-09-08 26 views
2

我有兩個數組 - $產品$ userProducts(這必須與兩個查詢完成,因爲我在尋找類產品在這個名字上,還有另一張桌子,我存儲了用戶想要出售的產品,並且我想向用戶展示他已經把這個產品出售了)。PHP - 搜索數組中,並添加屬性爲原來的數組,如果有一個積極的結果

$產品陣列看起來是這樣的:

[ 
    'id' => 1, 
    'name' => 'product name', 
    'synonim' => 'synonim'... 

], 
[ 
    'id' => 2, 
    'name' => 'product name 2', 
    'synonim' => 'synonim'... 

].... 

$ userProducts看起來是這樣的:

[ 
    'product_id' => 1 
], 
[ 
    'product_id' => 75 
] 

我想屬性添加到$產品陣列(或如果有更好的方法來做到這一點,那也可以)'userHasProduct' => true,如果$ userProducts包含product_id其中數字與ID$ products ID。我該如何做這項工作?

+3

爲什麼它必須是兩個單獨的查詢?因爲它看起來像一個左連接將解決你的問題 – Erik

+0

檢查這一個http://php.net/manual/en/control-structures.for.php –

+0

@Erik - 試過這個,我沒有得到我想要的結果(我不熟悉MySQL,所以有可能我沒有足夠的知識來編寫我需要的查詢)。 – Sasha

回答

4

同意@Erik,如果你可以修改你的原始查詢,那麼這可能是最好的解決在數據庫層。如果沒有,那麼你可以使用這樣的事情:

$products = array_map(function ($product) use ($userProducts) { 
    if (in_array($product['id'], array_column($userProducts, 'product_id'))) { 
    $product['found_in_user_products'] = true; 
    } 

    return $product; 
}, $products); 

這將循環遍歷您$products陣列中的每個條目,並在$userProducts的ID比較列表。如果找到了,那麼它將found_in_user_products鍵設置爲true。

工作例如:https://eval.in/858063

作爲參考,在SQL解決這個可能會是這個樣子:

​​

雖然明顯沒有看到您的架構很難說究竟

+1

不錯!我總是忘記'array_column' - 值得注意的是需要PHP 5.5+(每個人都應該在那個上面,但很多人仍然不會) –

+0

更好地將'array_column'移出循環,因爲沒有理由執行相同的任務每一次。 ( - ; – Neodan

1

如果查詢LEFT JOIN真的不會解決問題(我相信它會,順便說一句),然後我會推薦這樣的事情:

// flatten the array 
$ids = array_map(function($row) { 
    return $row['product_id']; 
}, $row); 

// loop over products (by reference) 
foreach($products AS &$row) { 
    // if the product ID is in the user's IDs array, set flag 
    if (in_array($row['product_id'], $ids) { 
     $row['userHasProduct'] = TRUE; 
    } 
} 
相關問題