gpt4 book ai didi

php - MongoDB 和 PHP 只获取匹配条形码的产品

转载 作者:可可西里 更新时间:2023-11-01 09:53:08 26 4
gpt4 key购买 nike

我有这个 JSON,你可以在产品下看到我有每个产品的条形码我想做的只是获取与产品条形码匹配的信息

{
"company": "village",
"logo": "http:\/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/villagetop.png",
"products": [
{
"barcode": "236690091",
"name": "Weekday",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "12.50",
"discount": "1.50"
},
{
"barcode": "236690092",
"name": "Weekend",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "13.50",
"discount": "1.60"
},
{
"barcode": "236690093",
"name": "Gold Class",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "13.50",
"discount": "1.60"
}
],
"store_name": "movies"
}

例如,如果我点击 236690091,我只返回数据库 (MongoDB)

"barcode": "236690091",
"name": "Weekday",
"logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"price": "12.50",
"discount": "1.50"

并非所有产品。

这是我试过的

public function getbarcode($barcode)
{
// select a collection (analogous to a relational database's table)
$collection = $this->db->movies->products;

// find everything in the collection
$cursor = $collection->find(array("barcode" =>"{$barcode}"));

$test = array();
// iterate through the results
while( $cursor->hasNext() ) {
$test[] = ($cursor->getNext());
}
//Print Results
print json_encode($test);

}

最佳答案

你不能这样做。 MongoDB 将始终返回完整文档,并且不允许您只返回要搜索的嵌套部分。我建议将产品拆分成自己的集合,然后将公司信息添加到每个产品。这也将规避 16MB 的文档限制,以防每家公司都有很多产品。

在不更改架构的情况下,以下代码应该可以工作:

public function getbarcode($barcode)
{
$products = array();
$collection = $this->db->movies->products;

foreach( $collection->find( array( 'products.barcode' => $barcode ) ) as $item )
{
foreach( $item->products as $product )
{
if ( $product['barcode'] == $barcode )
{
$products[] = $item;
}
}
}
return $products;
}

关于php - MongoDB 和 PHP 只获取匹配条形码的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9817478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com