PHP - 从键数组中获取嵌套数组的值

时间:2018-03-02 18:08:13

标签: php arrays loops nested

我有以下内容:

$values = Array (
          ['level1'] => Array (
             ['level2'] => Array(
                 ['level3'] => 'Value'
                 )
              )
          )

我也有一系列键:

$keys = Array (
          [0] => 'level1',
          [1] => 'level2',
          [2] => 'level3'
        )

我希望能够使用$ keys数组,因此我可以提出:$ values ['level1'] ['level2'] ['level3']。级别和键名称的数量将发生变化,因此我需要一个解决方案来读取我的$ keys数组,然后遍历$ values,直到得到最终值。

2 个答案:

答案 0 :(得分:1)

您可以迭代rand_int并存储$values,如下所示:

$ref

您还可以使用引用($ref = $values ; foreach ($keys as $key) { if (isset($ref[$key])) { $ref = $ref[$key]; } } echo $ref ; // Value )来避免数组的复制:

&

答案 1 :(得分:0)

class MyListConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Values())
        {
            var childToken = child.Children().First();
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(childToken.CreateReader(), newObject);
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}

希望这会有所帮助。当然删除<?php $values['level1']['level2']['level3'] = 'Value'; $keys = array ( 0 => 'level1', 1 => 'level2', 2 => 'level3' ); $vtemp = $values; foreach ($keys as $key) { try { $vtemp = $vtemp[$key]; print_r($vtemp); print("<br/>---<br/>"); } catch (Exception $e) { print("Exception $e"); } } 语句,但我尝试了它,最后它达到了值。直到它达到它不断击中数组的值,一次更深一层。