用数组PHP创建一个对象

时间:2015-02-11 12:11:58

标签: php arrays yii

我试图在整张桌子上搜索一个单词。 因此,如果您搜索Eminem,您必须使用Eminem这个词来获取所有内容。

我搜索

<?php

 $sql="SELECT * FROM album WHERE albumartiest like '$zoek'";
    $resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();                         
    if($resultaatcolumn != null){
     $zoekresultaat[] = $resultaatcolumn;}
 $sql="select * from album where albumnaam like '%$zoek%'";
    $resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
    if($resultaatcolumn != null){
     $zoekresultaat[] = $resultaatcolumn;}
 $sql="select * from album where albumartiest like '%$zoek%'";
    $resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
    if($resultaatcolumn != null){
     $zoekresultaat[] = $resultaatcolumn;}
 $sql="select * from album where albumgenre like '%$zoek%'";
    $resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
    if($resultaatcolumn != null){
     $zoekresultaat[] = $resultaatcolumn;}
 $sql="select * from album where albumafspeelijst like '%$zoek%'";
    $resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
    if($resultaatcolumn != null){
     $zoekresultaat[] = $resultaatcolumn;}

它有效,但不完全是我想要的。 结果如下:

Array ( [0] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) [1] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) )

没关系,但我想要的是取出变量并使用它。

有没有办法可以从变量中获取变量并使用它? 如果您想了解有关我的代码的更多信息,请询问!

3 个答案:

答案 0 :(得分:2)

尝试使用此

Yii::app()->db->CreateCommand($sql)->setFetchMode(PDO::FETCH_OBJ)->queryAll()

这将为您提供一组对象,其中列名称为

例如: -

foreach($result as $row)
{
echo $row->albumcode;
}

答案 1 :(得分:1)

如果要像对象一样访问结果集,可以使用本机PHP类ArrayObject并提供标记来指示。

$album = new ArrayObject($result, ArrayObject::ARRAY_AS_PROPS);

您现在可以访问以下结果:

$code = $album->albumcode;
$name = $album->albumnaam;

希望这可以指导你,快乐的编码!

答案 2 :(得分:0)

嗯,只是做

foreach($zoekresultaat as $key => $value) {
   //do what I want with each seperate returened result. The array key is in $key and the result array is in $value
   echo $value['albumcode'] . ' = '. $value['albumnaam'];

}

又名,基本的php

请为您的应用程序的安全性,学习如何在yii

中做好准备好的陈述

现在查询的方式我可以擦除整个数据库