php - 搜索多个对象的值时如何优化?
问题描述
希望一切都好。
假设我有这个对象 x 200(当然有不同的值)
[0] => stdClass Object
(
[Manufacturer] => Nike
[Name] => Air Max Talldress
[Options] => stdClass Object
(
[Black] => Array
(
[0] => Medium
[1] => Large
)
[White] => Array
(
[0] => Small
)
)
)
我只想要“制造商=耐克”的所有对象。我应该怎么做才能只与“制造商”属性进行比较,而不会在这种情况下不相关的属性上浪费时间。优化流程。
我对 dbms 不感兴趣,我想看看这里有什么可能。
// 新
解决方案
这可能会在你的路上帮助你......
为了重现问题并验证过滤器是否有效,我与制造商一起创建了一个虚拟数组,并生成了 100 个虚拟数据“对象”来迭代并找到持有某个制造商的那些。
<?php
$mans = ['Nike', 'Adidas', 'New Balance', 'Under Armour', 'Skechers', 'Asics', 'Saucony', 'Diadora', 'Fila', 'Anta'];
$arr = [];
// create a bunch of dummy data 'objects'
for($i=0; $i<10; $i++) {
foreach($mans as $key => $name) {
$arr[] = array("0" => (object)[
"Manufacturer" => $name,
"Name" => 'some model made by ' . $name,
"Options" => (object)[
"Black" => Array
(
"0" => 'Medium',
"1" => 'Large',
),
"White" => Array
(
"0" => 'Small'
)]
]
);
}
}
// filter for a manufacturer
$manufacturer = 'Nike'; // this is the manufacturer we are looking for
$result = filterMans($manufacturer, $arr); // $result is the array with all objects with the manufacturer we're looking for
$hits = count($result); // for each manufacturer in our list we get 10 hits
echo 'your search for objects with manufacturer ' . $manufacturer . ' returned ' . $hits . ' results';
echo '<br />';
echo '<pre>';
var_dump($result);
echo '</pre>';
function filterMans($needle, $haystack)
{
$result = null;
foreach($haystack as $key => $value) {
if($value[0]->Manufacturer === $needle) {
$result[] = $value[0];
}
}
return $result;
}
推荐阅读
- java - 如何将数组中的整数作为方法中的单独整数传递?
- python - 单独使用mutual_info_classif 和通过SelectKBest 使用时的不同分数
- c# - 模拟 Enter Key Press 从按钮的 Click 事件上发送?
- powershell - 从文本文件中检索值并将它们用作 PowerShell 中的变量
- oracle - 如何通过在 Oracle 中配对字符串来创建动态 sql
- apache-spark - Spark - 删除在 sql 提示中声明的广播变量
- typescript - 过滤承诺数组
- cypress - 如何使用 Cypress 使用 Chrome 配置文件(带有 arg '--user-data-dir')运行测试?
- wordpress - 2 具有相同蛞蝓的分类法
- java - 反序列化 Jackson 抽象类和多个具体类