打印出对象的键/值

时间:2016-02-03 19:01:30

标签: php arrays laravel laravel-5 blade

我有一个数组

DD($ vcpe)

array:23 [▼
  "cpe_mac" => "436291229311"
  "bandwidth_max_up" => 0
  "bandwidth_max_down" => 0
  "filter_icmp_inbound" => false
  "dmz_enabled" => false
  "dmz_host" => "192.168.1.1"
  "vlan_id" => 2
  "dns" => array:1 [▼
    0 => ""
  ]
  "xdns_mode" => 0
  "cfprofileid" => 11111
  "stub_response" => "0"
  "acl_mode" => 0
  "portal_url" => ""
  "fullbandwidth_max_up" => 1000000
  "fullbandwidth_max_down" => 2000000
  "fullbandwidth_guaranty_up" => 300000
  "fullbandwidth_guaranty_down" => 400000
  "account_id" => 1001
  "location_id" => 3333
  "network_count" => 3
  "group_name" => "test_group"
  "vse_id" => 20
  "firewall_enabled" => false
]

我想循环遍历它,并打印出键和值。

尝试#1

        @foreach ($vcpe as $key => $value)
          <p>{{$key}} : {{$value}}</p>
        @endforeach 

我得到了

htmlentities() expects parameter 1 to be string, array given

尝试#2

        @foreach ($vcpe as $key => $value)
          <p>{!!$key!!} : {!!$value!!}</p>
        @endforeach

我得到了

Array to string conversion

尝试#3

        @foreach ($vcpe as $key => $value)
          @foreach ($key as $k => $v)
            <p>{{$k}} : {{$v}}</p>
          @endforeach
        @endforeach

我得到了

Invalid argument supplied for foreach()

我做错了什么?

我该如何解决?

有人可以说明如何打印出对象的所有键/值?

1 个答案:

答案 0 :(得分:2)

正如我所看到的,$ value可能是一个数组。不幸的是,你没有只通过键循环,所以我不能确定。但我恳请你试试这个:

@foreach ($vcpe as $key => $value)
    @if (is_array($value))
        <p>{{$key}} :
        @foreach ($value as $value_key => $value_value) 
            {{$value_value}} 
        @endforeach
        </p>
    @else
        <p>{{$key}} : {{$value}}</p>
    @endif
@endforeach
相关问题