从数组PHP中的未定义索引获取值

时间:2016-03-16 10:17:40

标签: php arrays

我从请求中得到一个数组:

 $years['id'] = $request->get('years');

如果我做dd看起来像这样:

 array:3 [
  0 => "5"
  1 => "6"
  2 => "7"
  ]

在我的查询中,我想根据该数组中的值获取记录,如下所示:

qy.years_id whereIN ({$years['id']})

但是我收到了错误

Array to string conversion

我已经编辑了整个事情,这就是查询现在的样子:

$years = $request->get('years');
$subjects = $request->get('subjects');
$topics = $request->get('topics');
//get all the questions by given parameters
$qr =<<<SQL
SELECT
  count(DISTINCT q.id) AS questions_count
FROM
  questions q
LEFT JOIN
  question_year qy
ON
  q.id = qy.question_id
LEFT JOIN
  question_subject qs
ON
  q.id = qs.question_id
LEFT JOIN
  question_topic qt
ON
  q.id = qt.question_id
WHERE
  qy.year_id IN ({$years})
  SQL;
if ($subjects <> 0) {
    $qr .= <<<SQL
    AND
      qs.subject_id IN ({$subjects})
SQL;
}
if ($topics <> 0) {
    $qr .=<<<SQL
    AND
      qt.topic_id IN ({$topics})
SQL;
}
$result = $this->getReadConnection()->query($qr);
$result->setFetchMode(Db::FETCH_ASSOC);
$dboutput = array();

foreach ($result->fetchAll() as $key => $value) {
    $dboutput['count'] = $value['questions_count'];
}
return $dboutput;

但即使在这里我也会收到错误

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE),    expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

2 个答案:

答案 0 :(得分:2)

您需要像这样使用它:

"qy.years_id IN (" . implode(', ', $years['id']) . ")"

这应该适合你。

答案 1 :(得分:0)

也许这可以帮助您或向我们展示一些错误的代码。

$array = [5, 6, 7];

//  Method1:
echo $array[0]; // Returns 5

// Method3:
$buff = "";

// Method2:
foreach($array as $value){
    $buff .= $value; // For Method3
    echo $value; // Returns 567
}

echo $buff; // Returns 567