array_keys不在laravel中工作

时间:2017-07-12 09:16:13

标签: php mysql laravel

我想返回一个包含键的数组:

<?php
if(isset($values[0]->Content)):
$jarray= json_decode($values[0]->Content);
print_r(array_keys($jarray));
exit;
endif;
?>

$jarray的输出:

stdClass Object
(
    [_token] => QjyTAyDDUeadYvO0qj0gAZyK7OVyudSsY7Sq8Hhp
    [datefrom] => 2017-07-07
    [dateto] => 2017-07-31
    [Productivity] => test1
    [Productivityrating] => 2
    [Technical_Skills] => test2
    [Technical_Skillsrating] => 3
    [Work_Consistency] => test3
    [Work_Consistencyrating] => 4
    [Presentation_skills] => test4
    [Presentation_skillsrating] => 5
    [test] => test5
    [testrating] => 3
    [cycle_id] => 1
    [save] => proceed
)

我想返回一个包含键的数组,所以我试过

array_keys($jarray)

但它会出现错误,如

  

array_keys()期望参数1为数组,给定对象(查看:   我的路径)

预期产出:

Array
(
    [0] =>_token
    [1] => datefrom
    [2] =>_dateto
    [3] => Productivity
    [4] =>Productivityrating
    [5] => Work_Consistency
    [6] =>_Work_Consistencyrating

)etc

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

json_decode()返回默认情况下解码为object的json字符串(这就是为什么得到错误)。要将json解码为数组,您应该使用第二个参数等于true,如下所示:

$jarray = json_decode($values[0]->Content, true);

答案 1 :(得分:4)

由于您标记为Laravel,我建议使用Laravel的Key方法返回所有集合的键

$keys = $collection->keys();

$keys->all();

// ['prod-100', 'prod-200']

参考: Laravel Docs