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 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。