大佬教程收集整理的这篇文章主要介绍了php-如何解决此查询,使其仅返回其子数组中具有特定值的项目?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试修改投票脚本(Thumbsup),我需要此查询仅返回仅具有’cat’=>的数组项.子数组中的“ 1”(专有名词?)
<?PHP $items = ThumbsUp::items()->get() ?>
array (
0 =>
array (
'id' => 1,
'name' => 'a',
'cat' => '1',
),
1 =>
array (
'id' => 2,
'name' => 'b',
'cat' => '2',
),
2 =>
array (
'id' => 3,
'name' => 'c',
'cat' => '2',
),
)
编辑:继承人功能get()
public function get()
{
// Start building the query
$sql = 'SELECT id, name, url, cat, closed, date, Votes_up, Votes_down, ';
$sql .= 'Votes_up - Votes_down AS Votes_balance, ';
$sql .= 'Votes_up + Votes_down AS Votes_total, ';
$sql .= 'Votes_up / (Votes_up + Votes_down) * 100 AS Votes_pct_up, ';
$sql .= 'Votes_down / (Votes_up + Votes_down) * 100 AS Votes_pct_down ';
$sql .= 'FROM '.ThumbsUp::config('database_table_prefix').'items ';
// Select only either open or closed items
if ($this->closed !== NULL)
{
$where[] = 'closed = '.(int) $this->closed;
}
// Select only either open or closed items
if ($this->name !== NULL)
{
// Note: substr() is used to chop off the wrapping quotes
$where[] = 'name LIKE "%'.substr(ThumbsUp::db()->quote($this->name), 1, -1).'%"';
}
// Append all query conditions if any
if ( ! empty($where))
{
$sql .= ' WHERE '.implode(' AND ', $where);
}
// We need to order the results
if ($this->orderby)
{
$sql .= ' ORDER BY '.$this->orderby;
}
else
{
// Default order
$sql .= ' ORDER BY name ';
}
// A limit has been set
if ($this->limit)
{
$sql .= ' LIMIT '.(int) $this->limit;
}
// Wrap this in an try/catch block just in case something goes wrong
try
{
// Execute the query
$sth = ThumbsUp::db()->prepare($sql);
$sth->execute(array($this->name));
}
catch (PDOException $e)
{
// Rethrow the exception in debug mode
if (ThumbsUp::config('debug'))
throw $e;
// Otherwise, fail silently and just return an empty item array
return array();
}
// Initialize the items array that will be returned
$items = array();
// Fetch all results
while ($row = $sth->fetch(PDO::FETCH_OBJ))
{
// Return an item_id => item_name array
$items[] = array(
'id' => (int) $row->id,
'name' => $row->name,
'url' => $row->url,
'cat' => $row->cat,
'closed' => (bool) $row->closed,
'date' => (int) $row->date,
'Votes_up' => (int) $row->Votes_up,
'Votes_down' => (int) $row->Votes_down,
'Votes_pct_up' => (float) $row->Votes_pct_up,
'Votes_pct_down' => (float) $row->Votes_pct_down,
'Votes_balance' => (int) $row->Votes_balance,
'Votes_total' => (int) $row->Votes_total,
);
}
return $items;
}
谢谢.
解决方法:
public function get($cat = null)
{
$where = array();
if ($cat !== null) {
$where[] = 'cat = '. (int) $cat;
}
// ... original code ...
}
用法:
$items = ThumbsUp::items()->get(1);
以上是大佬教程为你收集整理的php-如何解决此查询,使其仅返回其子数组中具有特定值的项目?全部内容,希望文章能够帮你解决php-如何解决此查询,使其仅返回其子数组中具有特定值的项目?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。