【问题标题】:Laravel 4: Adding an extra key/value pair to array (object) retrieved from databaseLaravel 4:向从数据库检索的数组(对象)添加额外的键/值对
【发布时间】:2014-12-14 14:37:37
【问题描述】:

我想知道是否有人可以帮助我,因为我在这里开始感到沮丧......我有一个包含与图像相关的信息的数据库表。一列是“文件名”。检索到图像数组后,我想向名为“文件路径”的数组添加一个额外的键,格式为'/path/to/images' . array[$i]['filename']

够简单吧?但我似乎做不到(不使用一些荒谬的冗长代码)。这是我所拥有的:

    $array = DB::table('tour_images')->where('tour_id','=',$tourID)->get();
    $images = $array;
    $i = 0;
    foreach($array as $img){
        $images[$i]['filepath'] = '/upload/tour_images/' . $img['file_name'];
        $i++;
    }

但我得到 'Cannot use type of stdClass as array' 我猜这是因为第一行代码返回的是 object 而不是 array ,对吧?所以我尝试使用:

$array = DB::table('tour_images')->where('tour_id','=',$tourID)->get()->toArray();

猜猜看,它不起作用。好的,现在请有人帮助我...

编辑:从上面返回的错误:'在非对象上调用成员函数 toArray()'

【问题讨论】:

  • 你需要在toArray()之前调用get()->get()->toArray()
  • @lukasgeiter 我试过了 - 请参阅编辑。谢谢。
  • 为什么混合使用 foreach 和 $i?

标签: laravel laravel-4


【解决方案1】:

我个人只会处理这些对象。像这样:

$images = DB::table('tour_images')->where('tour_id','=',$tourID)->get();
foreach($images as $i => $img){
    $images[$i]->src = '/upload/tour_images/' . $img->file_name;
}

您也可以将其转换为数组。 toArray() 不起作用,因为它是一个普通对象数组,但将其转换为数组应该转换它。无论如何,您必须对结果集中的每一行都执行此操作。

$results = DB::table('tour_images')->where('tour_id','=',$tourID)->get();
$images = array();
foreach($results as $result){
    $img = (array) $result;
    $img['filepath'] = '/upload/tour_images/' . $img['file_name'];
    $images[] = $img;
}

【讨论】:

  • 谢谢,@lukasgeiter,您的第一个解决方案完美运行。好的,我需要记住在使用 Laravel 时尝试使用对象...否则我会尝试与系统对抗而不是使用它!谢谢。
【解决方案2】:

我以为$images 是一个数组,但$img 是一个stdClass

所以你应该使用-> 来引用它的属性

如下:

$images = DB::table('tour_images')->where('tour_id','=',$tourID)->get();

foreach($images as $img) {
    $img->filepath = '/upload/tour_images/' . $img->file_name;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 2021-07-01
    • 2016-06-25
    • 2012-01-21
    • 1970-01-01
    • 2014-09-29
    • 2017-01-12
    • 2016-03-18
    相关资源
    最近更新 更多