【问题标题】:MySQL column contains PHP array content, loopMySQL 列包含 PHP 数组内容,循环
【发布时间】:2016-10-05 13:15:29
【问题描述】:

我正在使用 Laravel 5.2。我在 MySQL 表中有一个文本(字符串)列,其中包含一个 PHP 数组,用于像这样的面包屑。

['employee.index' => 'Employees']

根据@weigreen 的建议,我还尝试了 JSON 格式的字符串内容,如下所示:

{'employee.index': 'Employees'}

然后我想在我的blade 模板中循环遍历它,如下所示:

@if($pageBreadcrumbs)
    @foreach($pageBreadcrumbs as $route => $name)
        @if ($name == end($pageBreadcrumbs))
            <li class="active">{!! $name !!}</li>
        @else
            <li><a href="{!! route($route) !!}">{!! $name !!}</a></li>
        @endif
    @endforeach
@endif

但我一直未能成功让 PHP 将此字段的内容解释为数组。

我已经尝试过这段代码的各种组合:

$breadcrumbsArray = array();
$breadcrumbsArray = $page->breadcrumbs;
View::share('pageBreadcrumbs', $breadcrumbsArray);

$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);

感谢任何帮助。

【问题讨论】:

  • 如何将数据存储到数据库中?作为字符串?
  • 嗨@weigreen,是的,字符串。
  • 我认为$breadcrumbsArray = $page-&gt;breadcrumbs; 行不通,也许您可​​以尝试将数据存储为 JSON 字符串?
  • 嗨@weigreen,我已经尝试过,但仍然没有运气。我已经更新了上面的问题以反映这一点。谢谢。

标签: php mysql arrays laravel-5 laravel-blade


【解决方案1】:

使用 Eloquent Mutators。 https://laravel.com/docs/master/eloquent-mutators

public function getBreadcrumbsAttribute($value)
{
    return json_decode($value, true);
}

这适用于您的“页面”模型。任何时候通过模型访问它都会将其变异为可用的数组。 (“true”的第二个参数强制执行数组)

其次,您可以使用 mutator 设置字段的值。

public function setBreadcrumbsAttribute($value)
{
    $this->attributes['breadcrumbs'] = json_encode($value);
}

然后你可以简单地做一些事情

foreach($page->breadcrumbs as $route => $title)...

$page->breadcrumbs = [['route' => 'Title'], ['other' => 'Other Title']];
$page->save();

【讨论】:

  • 嘿@jellis(或者我应该说 Zoolander)。你好吗?
  • 在没有你的桨的情况下惊人地上升el shittos creekos。然而,我还活着!
【解决方案2】:

这个答案真的是@weigreen 的。感谢您的帮助。

MySQL 内容的格式应该是:

{"employee.index": "Employees"}

然后在我的代码中读取行时,我这样做:

$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);

完美运行。

【讨论】:

    【解决方案3】:

    尝试转换回php对象并使用它。

    如果你不转换它,你的数据将被 php 视为字符串。

    $breadcrumbsArray = json_decode($page->breadcrumbs);
    View::share('pageBreadcrumbs', $breadcrumbsArray);
    

    【讨论】:

    • 嗨@weigreen,我也试过了。我的代码现在没有失败,但它不会生成面包屑。 json_decode 的结果是 null 尽管传递给它的内容是正确的 {'client.index': 'Clients'}
    • @TheRealPapa 使用 json_encode 获取您的 json 字符串。我试过如果我使用{"client.index": "Clients"} 它可以工作。 (在字符串中使用双引号
    猜你喜欢
    • 2020-06-28
    • 2017-11-07
    • 2016-01-11
    • 2018-01-21
    • 2012-07-13
    • 2023-03-05
    • 2011-05-25
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多