2018-11-17 02:03
浏览 880


I am very new to both PHP and Laravel. I want to dump specific information out of an array. I prefer not to use a foreach loop as I know the one I want.

Here is the array :

enter image description here

I want to display ICAR - Intermediate

I have tried :








I am sure this is something simple that I am missing in the syntax but I can't figure it out. Without using a for loop to loop through every key and value how can I get both the key ICAR and the code part of the value of a given pair?


Both of the responses below from @newUserName02 and @Carlos Gurrero partially give me what I need


does work IF I know I am looking for ICAR but if I only know I need the information from the 3rd position how do I get

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • ds2010630 2018-11-17 02:25

    You have to get the values in an array by their keys. This is an associative array with strings as keys, with an object nested inside.

    Quick breakdown of your example:

    • The value at the key 'ICAR' is an array with 2 other keys: 'code' and 'vehicle_name'
    • The value at the key 'code' is an object with one property: code

    To access the value inside you can do this:

    // this will get you the value 'Intermediate'

    NOTE: PHP allows you to have any string or integer as an array key, so the following is a perfectly valid array:

    $array = [
        0 => 'first index',
        1 => 'second index',
        '' => 'empty string key',
        'anotherkey' => 'string key',
        'nested' => [
            'nested' => [
                'nested' => 'etc'
            0 => [
                0 => 'hello',
                1 => 'world',
    dump($array[0]);                            // 'first index'
    dump($array[1]);                            // 'second index'
    dump($array['']);                           // 'empty string key'
    dump($array['anotherkey']);                 // 'string key'
    dump($array['nested']['nested']['nested']); // 'etc'
    dump($array['nested'][0][0]);               // 'hello'

    As for getting 'ICAR' it depends. Since it isn't a value in the array, and you already know that's the specific thing you want, you could just code it in where you need it.

    echo 'ICAR - ' . $listofcarcodesnames['ICAR']['code']->code;

    EDIT: if you don't know what the exact key name is, but you happen to know it's the 3rd one, you can do something like this:

    $count = 0;
    foreach($listofcarcodesnames as $key => $val) {
        if($count === 2) {
            echo $key . ' - ' . $listofcarcodesnames[$key]['code']->code;

    But be careful with this method. When inside PHP, the keys in an associative array will maintain the same order. But if you're passing data between PHP and JavaScript, then the JS object's keys are NOT guaranteed to have a consistent order.

    Does JavaScript Guarantee Object Property Order?

    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题