如何创建查询以获取使用where子句作为结果数组索引的结果?

时间:2012-08-16 15:59:03

标签: php mysql

这是我使用的查询:

$idList="32,33,21,11";          
$query = "SELECT post_id, meta_value FROM wp_posts 
          WHERE meta_key = 'grade' AND post_id IN ($idList)";

结果,where子句成为键:

$result = array(
              0 => array('post_id'=> 32, 'meta_value'=>5),
              1 => array('post_id'=> 33, 'meta_value'=>2),
              2 => array('post_id'=> 21, 'meta_value'=>8),
           )

我希望得到这样的结果:

$result = array(
              0 => array( 32 => 5 ),
              1 => array( 33 => 2 ),
              2 => array( 21 => 8 ),
           )

如何实现这一目标?谢谢!

1 个答案:

答案 0 :(得分:1)

循环遍历结果集,如下所示:

$_final = array(); // new result set

foreach ($result as $value)
  $_final[] = array($value['post_id'] => $value['meta_value']);

unset($result); // free memory from old result set

UPDATE:如果元素太多并且您害怕内存消耗,您可以通过以下方式执行此操作:

$_final = array(); // new result set

foreach ($result as $key => $value) {
  $_final[] = array($value['post_id'] => $value['meta_value']); // composing new data
  unset($result[$key]); // unsetting already parsed value
}

unset($result); // freeing memory from old result set