打印出 key/value 个对象

Print out key/value of an object

我有一个数组


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()

我做错了什么?

我该如何解决?

有人可以告诉我如何打印出一个对象的所有 key/value 吗?

在我看来,$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