从数组中创建一个对象 PHP

make an object out of an array PHP

我正在尝试在整个 table 中搜索一个词。 因此,如果您搜索 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 ) ) )

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

有没有办法从数组中取出变量并使用它? 如果你们想要更多关于我的代码的信息,请询问!

嗯嗯就这样吧

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 中执行准备好的语句

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

如果您想像访问对象一样访问结果集,您可以使用本机 PHP class ArrayObject 并提供标志来表明这一点。

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

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

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

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

试试这个

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

这将为您提供一个对象数组,其中 列名称作为属性

例如:-

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