开发者

PHP: What is the Best Way To Search Through Values?

I'm not sure what the best way and quickest way to search through values.

I have a check list of up to 20 ids that look like the example below. But they can be stored as an array too.

'6e0ed0ff736613fdfed1c77dc02286cbd24a44f9','194809ba8609de16d9d8608482b988541ba0c971','e1d612b5e6d2bf4c30aac4c9d2f66ebc3b4c5d96'....

What i do next is get another set of items from a json api call as a php stdclass. When i loop through those items I add html for each item to d开发者_JAVA百科isplay back on my website. If one of the item's id matches the ids in the checklist then i would add different html

I'm doing all this in an ajax call so what is the best and most efficient way to search through that checklist?

for example

    //get a list of ids from DB and store in $checklist

$checklist;

$data = file_get_contents($url);
    $result = json_decode($data, true);

foreach ( $result->results as $items )
    {
        $name = $items->name;
        $category = $items->category;
        $description = $items->description;
        $id = $items->id;

        // if ID is in $checklist then use blue background.
        $displayhtml .="<div style=\"background-color: white;\">";  
        $displayhtml .="<h3>".$name."</h3>";
        $displayhtml .="<p>".$description."</p>";
        $displayhtml .="</div>";

    }

Thanks.


The simple way (if you're using PHP to do this) is to use in_array()

$checklist = array(
    '6e0ed0ff736613fdfed1c77dc02286cbd24a44f9',
    '194809ba8609de16d9d8608482b988541ba0c971',
    'e1d612b5e6d2bf4c30aac4c9d2f66ebc3b4c5d96',
    'etc.'
);
foreach ($items as $id) // $items are a similar array of ids you're checking
{
    if ( ! in_array($id, $checklist))
    {
        // not in the checklist!
    }
}

Per your example:

foreach ( $result->results as $items )
{
    $name = $items->name;
    $category = $items->category;
    $description = $items->description;
    $id = $items->id;

    // if ID is in $checklist then use blue background.
    if (in_array($id, $checklist))
    {
        $bg = 'blue';
    }
    else
    {
        $bg = 'white'
    }
    $displayhtml .='<div style="background-color: '.$bg.';">'; 
    $displayhtml .="<h3>".$name."</h3>";
    $displayhtml .="<p>".$description."</p>";
    $displayhtml .="</div>";

}

There are more elegant ways to handle this, but you didn't ask for a rewrite. Personally, for starters I would add a css class instead of inlined style, but hopefully this gets you moving forward.


I would create 2 arrays from both sets and use array_intersect() to extract overlapping ids

http://www.php.net/manual/en/function.array-intersect.php

$array1 = array(123,234,345,456,567);
$array2 = array(321,432,345,786,874);
$result = array_intersect($array1, $array2);

// Results in: $result = array( 345 )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜