【问题标题】:Outputting single json object from array从数组中输出单个 json 对象
【发布时间】:2017-04-23 12:28:32
【问题描述】:

在 laravel 中,我试图将 json 数据传递到我的 profile.blade.php 视图中。我的 apicontroller.php 中有 json 查询,它从我的配置文件数据库表中提取数据,然后使用 profilecontroller.js 将数据传递到 profile.blade.php。

我可以使用 @{{ profiles }} 在 profile.blade.php 中将数据视为数组,我得到了输出

[{"id":1,"username":"test","email":"test@gmail.com","password":"$2y$10$q2N/p3AD8FfUHxRVOF.aoecIKy8qcOBgvVurP4tZrcRdvZSS3JDOK","avatar":"default.jpg","remember_token":null,"created_at":"2016-12-07 22:29:57","updated_at":"2016-12-07 22:29:57"}]

但如果我尝试获取单个对象,例如 {{ profiles.username }} 它不会输出任何内容

如何从我的数组中只提取用户名或其他对象?

apiController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\UserDetail;
use App\Users;
use View;
use Auth;

class ApiController extends Controller
{
public function showAll()
{
    return response()->json(
    $details = Users::get()
    );

    }
}

profilecontroller.js

app.controller('profileController', function($scope, $http) {

$http.get('/api/hello')
.success(function(data, status, headers, config) {
 $scope.profiles = data;
})
.error(function(error, status, headers, config) {
 console.log(status);
 console.log("Error occured");
});

profile.blade.php

@ {{profile}} 

【问题讨论】:

  • 您使用什么 javascript 框架来执行此操作?你能发布你正在使用的整个视图吗?
  • 你的对象在一个数组中。你应该做的是:{{ profiles[0].username }}
  • 感谢完美,忘了说这是使用角度

标签: php mysql arrays json laravel-5


【解决方案1】:

您的对象在一个数组中,因此您必须指出您的代码所引用的数组条目,即使数组中只有一个条目。

数组索引为零,因此数组中的第一项将始终具有索引 [0]

因此

@{{ profiles[0].username }}

应该实现你想要做的事情。

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2022-07-20
    • 2021-07-31
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多