LoginSignup
8
8

More than 5 years have passed since last update.

ドットつなぎの文字列で連想配列にアクセスする関数

Last updated at Posted at 2014-03-18

個人的に必要だったので作成。
同じ引数で何度も処理するのは良くないと思ったので静的変数でプチキャッシュしてる。

array_dot_access.php
<?php

function array_dot_access( $str = NULL ) {
    if( empty($str) || !is_string($str) ) {
        return false;
    }

    static $buffer=array();

    if( !empty($buffer[$str]) ) {
        return $buffer[$str];
    }

    //元となる配列
    $array = array(
        'keyA'=>array(
            'keyB'=>array(
                'keyD'=>'OK'
            )
        ),
    );

    $ex = explode('.', $str);
    $return = NULL;
    for ( $i=0, $l=count($ex)-1; $i<=$l; $i++ ) {
        if( 0 === $i ) {
            if( !array_key_exists($ex[$i], $array) ) {
                break;
            }
            $return = $array[$ex[$i]];
        } else {
            if( !is_array($return) || !array_key_exists($ex[$i], $return) ) {
                $return = NULL;
                break;
            }
            $return = $return[$ex[$i]];
        }
    }

    if(!empty($return)){
        $buffer[$str] = $return;
    }

    return $return;
}


/*
Example

var_dump(array_dot_access('keyA.keyB.keyD')); // string(2) "OK"

var_dump(array_dot_access('keyA.keyB')); // array(1) { ["keyD"]=> string(2) "OK" }

var_dump(array_dot_access('keyA.keyZ')); // NULL

*/
8
8
2

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
8
8