1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel とPHP TipsAdvent Calendar 2023

Day 3

data_getヘルパで連想配列から値を取り出そう!

Last updated at Posted at 2023-12-06

概要

data_get関数は「ドット」記法を使用し、ネストした配列やオブジェクトから値を取得します。
値が存在しない場合はnullを返却し、第三引数に値が存在しなかった場合に返却する値を設定できます.

$threeDimensionalArray = array(
    'first_level' => array(
        'first_level_key_1' => 'Value 1',
        'first_level_key_2' => 'Value 2',
        'second_level' => array(
            'second_level_key_1' => 'Value 3',
            'second_level_key_2' => 'Value 4',
            'third_level' => array(
                'third_level_key_1' => 'Value 5',
                'third_level_key_2' => 'Value 6',
            ),
        ),
    ),
    'second_level' => array(
        'first_level_key_3' => 'Value 7',
        'first_level_key_4' => 'Value 8',
        'second_level' => array(
            'second_level_key_3' => 'Value 9',
            'second_level_key_4' => 'Value 10',
            'third_level' => array(
                'third_level_key_3' => 'Value 11',
                'third_level_key_4' => 'Value 12',
            ),
        ),
    ),
);

dd(data_get($threeDimensionalArray, 'first_level.first_level_key_1'));
//Value 1

オブジェクトでも使用できます

$threeDimensionalArray = (object) array(
    'first_level' => (object) array(
        'first_level_key_1' => 'Value 1',
        'first_level_key_2' => 'Value 2',
        'second_level' => (object) array(
            'second_level_key_1' => 'Value 3',
            'second_level_key_2' => 'Value 4',
            'third_level' => (object) array(
                'third_level_key_1' => 'Value 5',
                'third_level_key_2' => 'Value 6',
            ),
        ),
    ),
    'second_level' => (object) array(
        'first_level_key_3' => 'Value 7',
        'first_level_key_4' => 'Value 8',
        'second_level' => (object) array(
            'second_level_key_3' => 'Value 9',
            'second_level_key_4' => 'Value 10',
            'third_level' => (object) array(
                'third_level_key_3' => 'Value 11',
                'third_level_key_4' => 'Value 12',
            ),
        ),
    ),
);

dd(data_get($threeDimensionalArray, 'second_level.second_level.third_level.third_level_key_4'));
//Value 12

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?