2

I have an array like this:

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

I can access x.y like this:

array_get($data, 'x.y');

However, how can I access x.(a.b) (sometimes written as x.a->b)

I tried the following:

array_get($data, 'x.a.b');
array_get($data, 'x.a->b');

But neither seems to work.

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

4 Answers4

4

You can't do it with array_get. If you take a look at the function (vendor/laravel/framework/src/Illuminate/Support/helpers.php:155):

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

Which calls the get function of the Arr class (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;
}

If you take a look at the foreach loop which handles the ., it does not support the structure your array has.

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
1
`<?php
$data = [
  "x" => [
    "y" => 5,
    "a.b" => 10
  ]
];
echo $data['x']['a.b'];
// get like this
?>`

if you are accessing from db use aliases as mentioned in below link php object attribute with dot in name

Harshavardhan
  • 352
  • 1
  • 6
0

It's quite simple, based on your example:

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

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

You actually don't have to use array_get for an array as this though. And also why would you use such a name for your array index.

0
public function getNestedArr($array, $key, $default = null)
    {

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

        foreach (explode(',', $key) as $segment) {
            $array = $array[$segment];
        }

        return $array;
    }
$array = ['GrandParent' => ['parent' => ['childs' => 'xyz']]];
    $data = $this->getNestedArr($array, 'GrandParent,parent,childs');
    print_r($data);

Answer is "xyz"

I'm not sure this'll solve your problem, but it's very useful when you get the value from nested array

Musawer Ali
  • 1
  • 1
  • 1
  • Your answer does not match what is asked for in the question, it is suggested to review your answer – bhucho Feb 01 '22 at 15:36