PHP:通过价值观搜索的最佳方式是什么?

时间:2011-07-22 15:44:43

标签: php ajax

我不确定搜索价值的最佳方式和最快捷方式。

我有一个最多20个ID的检查清单,如下例所示。但它们也可以存储为数组。

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

我接下来要做的是从json api调用另一组项目作为php stdclass。当我遍历这些项目时,我为每个项目添加html以显示在我的网站上。如果项目的id中的一个与核对表中的ID匹配,那么我将添加不同的html

我在ajax调用中做了所有这些,那么搜索该核对表的最佳和最有效的方法是什么?

例如

    //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>";

    }

感谢。

2 个答案:

答案 0 :(得分:3)

简单的方法(如果您使用PHP来执行此操作)是使用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!
    }
}

根据你的例子:

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>";

}

有更优雅的方法可以解决这个问题,但你没有要求重写。就个人而言,首先我会添加一个css类而不是内联样式,但希望这会让你前进。

答案 1 :(得分:3)

我将从两个集合中创建2个数组,并使用array_intersect()来提取重叠的ID

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 )
相关问题