how to turn array key into property so I can access it as property

时间:2017-04-10 01:29:21

标签: php arrays laravel object

I have an array of settings and I would like to access it like :

$settings->type

instead of :

$settings['type']

inside of blade. I prefer the first version since its more elegant.

here is my array:

array:5 [▼
  "enable" => "true"
  "type" => "native"
  "must_be_registered" => "true"
  "allow_nested" => "true"
  "nested_level" => "5"
]

I tried turning it into collection

Collection {#382 ▼
  #items: array:5 [▼
    "enable" => "true"
    "type" => "native"
    "must_be_registered" => "true"
    "allow_nested" => "true"
    "nested_level" => "5"
  ]
}

but that did not help really, I still could not do $settings->type inside blade, anyone knows how I can do this?

Property [type] does not exist on this collection instance.

2 个答案:

答案 0 :(得分:2)

Well try this work around:

$array=[
  "enable" => "true",
  "type" => "native",
  "must_be_registered" => "true",
  "allow_nested" => "true",
  "nested_level" => "5"
];

$settings=json_decode(json_encode($array));

echo $settings->type;

Or

$settings=(Object)$array;

echo $settings->type;

答案 1 :(得分:1)

You can use (object)array like this,

<?php

$array=[
  "enable" => "true",
  "type" => "native",
  "must_be_registered" => "true",
  "allow_nested" => "true",
  "nested_level" => "5"
];

$settings=(object)$array;

echo $settings->type;

demo here.

相关问题