我有一个类似
的json对象$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
我可以从中获得这样的价值
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
如果密钥存储在变量
中$key= '["toppings"][2]["type"]';
如何从json对象$ yummy获取值。
我试过了
$d= $yummy.$key;
我在变量中提供了密钥,因此我不知道密钥和密钥名称的数量。 Json对象和键是动态创建的。
答案 0 :(得分:0)
一旦执行了json_decode,就可以在数组中获得内容,这样就可以将var用作数组的索引
但你的字符串不是,并且数组的索引只是一个字符串,所以你应该使用一组var来获取索引集(或者你管理你的字符串以构建一组var)例如:
$key1 = 'toppings';
$key2 = 2;
$key3 = 'type';
echo = $yummy[$ke1][$key2][$key3];
答案 1 :(得分:0)
你可以使用func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "userDetailsCell", for: indexPath) as! UserDetailsCustomCell
let dataSource = UserDetailsObjectModel("insert the data in each param!")
cell.dataSouece = dataSource
return cell
}
,但不鼓励使用{},我有义务先在documentation中复制免责声明:
<强>注意强>
eval
语言构造非常危险,因为它允许执行任意PHP代码。因此不鼓励使用它。如果您已经仔细验证除了使用此构造之外没有其他选择,请特别注意不要将任何用户提供的数据传递到其中,而不事先正确验证它。
您应该查看其他编码密钥序列的方法。但为了以防万一,您可以使用eval()
:
eval
在没有echo eval("return \$yummy$key;");
的情况下执行此操作的方法是迭代eval
字符串中的键,并随时查找结果值:
$key