【发布时间】:2018-08-28 09:25:17
【问题描述】:
我在数据库中查询图像列表:
$rows = $db->table('images')->where('attivo', 1)->get();
我得到以下对象:
object(Illuminate\Support\Collection)#107 (1) {
["items":protected]=>
array(5) {
[0]=>
object(stdClass)#96 (12) {
["id"]=>
int(3)
["img"]=>
string(11) "example.jpg"
["created_at"]=>
string(19) "2018-07-26 20:33:59"
["attivo"]=>
int(1)
}
[1]=>
object(stdClass)#88 (12) {
["id"]=>
int(4)
["img"]=>
string(12) "img.png"
["created_at"]=>
string(19) "2018-07-26 20:33:59"
["attivo"]=>
int(1)
}
[2]=>
object(stdClass)#103 (12) {
["id"]=>
int(5)
["img"]=>
string(9) "test2.jpg"
["created_at"]=>
string(19) "2018-07-27 13:42:13"
["attivo"]=>
int(1)
}
}
}
我需要修改img值,把url的头部(http://www.example.com/folder/)放在它之前,然后在发送到json编码之前将值重写回对象。
我尝试了以下方法,但可能是我解决问题的方法有误。
foreach ($rows as $k => $value) {
if($k == 'img'){
echo $rows['img'] = "http://example.com/folder/".$value->img;
}
}
你能给我一个方向吗?
【问题讨论】:
-
$directory的值是多少?您是否注意到您尝试在每次迭代中更改$rows而不是$value?还有一个each助手,我认为在这种情况下会帮助你 laravel.com/docs/5.6/collections#method-each -
为什么你对我的问题投了反对票?请给个理由...
-
@Nima 是的,我正在尝试重写
$rows['img'],正如我在问题中所写的那样 -
$rows是一组对象,其中每个对象都有一个img属性,而不是$rows本身。还遍历所有对象属性(我认为您打算这样做,但您的代码实际上没有这样做)以找到img键,然后对其进行处理很奇怪并使您的问题不清楚,因为您可以简单地使用['img']或->img访问该密钥/属性。请举例说明您的代码的当前输出和所需输出。
标签: arrays object eloquent slim