如何循环(foreach)在php(laravel)中解码的json

时间:2019-01-25 02:33:10

标签: php laravel-5

这是我的代码`

$a =json_decode($user->name, true);

我需要循环$a,但是我得到

  

“为foreach提供了无效的参数”

执行时 `

3 个答案:

答案 0 :(得分:0)

您可以在数组中循环,我认为此$a =json_decode($user->name, true);

的结果

是字符串

答案 1 :(得分:0)

根据您在其他答案中发布的内容以及对我的评论,您需要将循环更改为此:

fade

请注意从.modal("show")更改为foreach($a[0] as $akey => $aloop) { array_push($array, $aloop->email)); }

答案 2 :(得分:0)

您应该向我们描述JSON字符串的样子。

也许您可以在下面尝试以下代码:

$user= '[{"name":"Jonathan Suh","email":"jonathan.suh@gmail.com"},
              {"name":"William Phil","email":"will.phil@gmail.com"},
              {"name":"Allison Kin","email":"allison.kin@gmail.com"}]';

// Replace with your own JSON
$a = json_decode($user, true); // Array

// Create empty array to hold query results
$array = [];

// Begin loop ( foreach )
foreach ($a as $akey => $aloop) {
    array_push($array, ['name' => $aloop["name"], 'email' => $aloop["email"]]);
}

// Encode your array result from Loop Process to JSON
// You can change whatever you want to do from your Result Loop
$jsonENC = json_encode($array);

// You know what is this...
echo $jsonENC;