在多个对象中搜索值时如何优化?

时间:2018-07-15 20:44:30

标签: php object optimization iteration scanning

希望一切都很好。

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


// 新

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助...

为重现问题并验证过滤器的工作原理,我与制造商一起创建了一个虚拟阵列,并生成了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;
}