首页 > 解决方案 > 搜索多个对象的值时如何优化?

问题描述

希望一切都好。

假设我有这个对象 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 不感兴趣,我想看看这里有什么可能。


// 新

标签: phpobjectoptimizationiterationscanning

解决方案


这可能会在你的路上帮助你......

为了重现问题并验证过滤器是否有效,我与制造商一起创建了一个虚拟数组,并生成了 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;
}

推荐阅读