为什么这个PHP“in_array”不能用于SQL查询?

时间:2014-06-23 20:39:56

标签: php sql wordpress

您好我有一些wordpress帖子,其中包含一个标题为“#34; Incentive ID"”的自定义字段。我有一个php / sql查询,返回逗号分隔的"推荐" "奖励ID"

global $wpdb;
$user_ID = get_current_user_id();
$sql = <<<SQL
SELECT GROUP_CONCAT(T_L_INCENTIVES_ID) 
FROM incentive_recommendations_v 
WHERE accept_recommendation = 1 AND user_id = $user_ID
SQL;

if (!$sql) { // add this check.
    die('Invalid query: ' . mysql_error());
}

$resultset = array();
$rebates = $wpdb->get_results( $sql, ARRAY_A );
foreach($rebates as $data) {
     $resultset[] = $data['GROUP_CONCAT(T_L_INCENTIVES_ID)'];
}

我想填一个特别的奖牌&#34;每个帖子上的图标,其自定义字段值为&#34;奖励ID&#34;包含在逗号分隔列表中的&#34;推荐&#34;奖励ID。为此,我试图使用&#34; in_array&#34;像这样

<?php while ( have_posts() ) : the_post(); ?>
<li style="margin-bottom:20px;">
<?php echo $resultset;?><br>
<?php echo get_post_meta(get_the_ID(), 'Incentive ID', true);?>
<div title="Recommended Incentive" <?php $incent = get_post_meta(get_the_ID(), 'Incentive ID', true); if ( in_array($incent,$resultset)) { 
echo'style="background-image:url(/images/gold_medal.jpg); background-repeat:no-repeat; background-size:10% auto; background-position:right top; border:2px solid #ccc; padding:20px 48px 20px 20px; height:auto; padding-bottom:20px; min-height:260px !important;"';
} else { 
echo 'style="border:2px solid #ccc; padding:20px 48px 20px 20px; height:auto; padding-bottom:20px; min-height:260px !important;"';}  ?> >

但是,我根本无法显示金牌图标,即使是在我知道包含正确的&#34;激励ID&#34;的帖子上也是如此。我收到的错误是

in_array expects parameter 2 to be array, string given.  

非常感谢您对此问题提供的任何帮助!

2 个答案:

答案 0 :(得分:0)

GROUP_CONCAT()将生成一个字符串,因此您的数据库结果将类似于

$rows = array(
   '0' => array('foo' => '1,2,3,4'),
   '1' => array('bar' => '5,6,7,8')
);

你真的想要做in_array(3, '1,2,3,4')。由于1,2,3,4是一个字符串,因此您会收到警告。您需要explode()该字符串,然后在您从explode()获得的数组上执行in_array。或者只是不要在数据库中执行group_concat并将单个记录提取到您在while / fetch循环中构建的数组中。

答案 1 :(得分:0)

首先从GROUP_CONCAT()语句中删除SELECT 然后,添加GROUP BY语句也添加SELECT。 以下是SELECT语句的代码并将其转换为数组。

global $wpdb;
$user_ID = get_current_user_id();
$sql = <<<SQL
SELECT T_L_INCENTIVES_ID
FROM incentive_recommendations_v 
WHERE accept_recommendation = 1 AND user_id = $user_ID
GROUP BY T_L_INCENTIVES_ID
SQL;

if (!$sql) { // add this check.
    die('Invalid query: ' . mysql_error());
}

$resultset = array();
$rebates = $wpdb->get_results( $sql, ARRAY_A );
foreach($rebates as $data) {
     $resultset[] = $data['T_L_INCENTIVES_ID'];
}

然后将您的代码更改为此以填充“金牌”图标

<?php $incent = get_post_meta(get_the_ID(), 'Incentive ID', true); if ( in_array($incent,$resultset)) { 
          echo'style="background-image:url(/images/gold_medal.jpg); background-repeat:no-repeat; background-size:10% auto; background-position:right top; border:2px solid #ccc; padding:20px 48px 20px 20px; height:auto; padding-bottom:20px; min-height:260px !important;"';
          } else { 
          echo 'style="border:2px solid #ccc; padding:20px 48px 20px 20px; height:auto; padding-bottom:20px; min-height:260px !important;"';}  ?>