Laravel 5:如何使用array_get方法访问内部带有点的属性

时间:2018-07-03 12:30:42

标签: laravel laravel-5 laravel-5.6

我有一个像这样的数组:

2018-07-03 17:52:12 ERROR RecordBatch:102 - Error executing user-provided callback on message for topic-partition test-2:
java.lang.NullPointerException
    at com.spnotes.kafka.partition.Producer$1.onCompletion(Producer.java:29)
    at org.apache.kafka.clients.producer.internals.RecordBatch.done(RecordBatch.java:99)
    at org.apache.kafka.clients.producer.internals.RecordBatch.maybeExpire(RecordBatch.java:136)
    at org.apache.kafka.clients.producer.internals.RecordAccumulator.abortExpiredBatches(RecordAccumulator.java:220)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:192)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:141)
    at java.lang.Thread.run(Thread.java:748)

我可以这样访问$data = [ "x" => [ "y" => 5, "a.b" => 10 ] ]

x.y

但是,我如何访问array_get($data, 'x.y'); (有时写为x.(a.b)

我尝试了以下操作:

x.a->b

但是似乎都不起作用。

3 个答案:

答案 0 :(得分:2)

您无法使用array_get来做到这一点。如果您看一下功能( vendor / laravel / framework / src / Illuminate / Support / helpers.php:155 ):

function array_get($array, $key, $default = null)
{
    return Arr::get($array, $key, $default);
}

哪个调用Arr类的get函数( vendor / laravel / framework / src / Illuminate / Support / Arr.php:278 ):

public static function get($array, $key, $default = null)
{
    if (! static::accessible($array)) {
        return value($default);
    }

    if (is_null($key)) {
        return $array;
    }

    if (static::exists($array, $key)) {
        return $array[$key];
    }

    if (strpos($key, '.') === false) {
        return $array[$key] ?? value($default);
    }

    foreach (explode('.', $key) as $segment) {
        if (static::accessible($array) && static::exists($array, $segment)) {
            $array = $array[$segment];
        } else {
            return value($default);
        }
    }

    return $array;
}

如果您看一下处理.的foreach循环,它不支持数组的结构。

答案 1 :(得分:1)

`<?php
$data = [
  "x" => [
    "y" => 5,
    "a.b" => 10
  ]
];
echo $data['x']['a.b'];
// get like this
?>`

如果要从数据库访问,请使用以下链接中提到的别名 php object attribute with dot in name

答案 2 :(得分:0)

根据您的示例,这很简单:

$data = [
  "x" => [
    "y" => 5,
    "a.b" => 10
  ]
];

array_get($data, "x")['a.b'] //gives you the right value

您实际上不必为数组使用array_get,尽管如此。还有为什么要为数组索引使用这样的名称。