duanlianyun0462 2015-03-24 08:59
浏览 45
已采纳

PHP / MySQL在数组中搜索特定值

In a WordPress environment I'm creating pages that represent a company page. These company pages sell certain brands. So I created a custom form in a metabox that let's the user dynamically add fields to add the amount of brands they sell. These values are stored in an array in my database.

The problem I'm having now is that I want to create some sort of filter. I created a page that shows all images of the possible brand logos. These logos are having a link with a custom value added to it (brandname). For example:

<a href="somepage.php?brand='brandname'"><img src="brandname.jpg"></a>

On the page that follows I do a get request to retrieve the value added to the url. With this value I would like to show all the companies that are selling the brand.

The last part of this is the problem. I don't know how to search in an array with the value added to the URL.

So I figured I need an SQL statement to SELECT * FROM $wpdb->postmeta WHERE the database meta_key field = 'brand' and the meta_value = the GET['brand'] from the url and found in the array.

-- UPDATE --
So I tried the solution from DiegoCoderPlus but give me not what I want:

global $post;
$merk = $_GET['merk'];
$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = 'brand'");
foreach ($results as $result){
    $post_id = $result->post_id;
    $brand = get_post_meta($post_id, 'brand', false); 
    $brandNeedle = $merk;                   
    if(in_array($brandNeedle, $brand))
        {
            echo 'true<br>';
        }else
        {
            echo 'false<br>'; 
        }
    }

This gives me as a result two times false. Which is half good because there are only two companies in my database for testing. If I use a different brand it also shows two false results.
the $brand array looks like this. Maybe it helps:

Array
(
    [0] => Array
        (
            [0] => 
        ) 

)

false

Array
(
    [0] => Array
        (
            [0] => brand 1
            [1] => brand 2
        )

)
  • 写回答

1条回答 默认 最新

  • doutun9179 2015-03-24 09:24
    关注

    if your array is a php one, the only thing you need is in_array

    it works like this:

    $brands = array('brand1', 'brand2', 'brand3', 'brand4');
    $brandNeedle = 'brand2';
    
    if(in_array($brandNeedle, $brands))
    {
       // it is on the array
    }else
    {
       // it is not 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?