PHPプログラムに関する各種メモ書き

PHPでハッシュの配列を検索する

PHPでよくあるこういうデータ

$data = [
  0 => [
    "name" => "client" ,
    "type" => "string" ,
    "arguments" => [] ,
    "options" => [
      "nullable" => false
    ]
  ] ,
  1 => [
    "name" => "company" ,
    "type" => "string" ,
    "arguments" => [] ,
    "options" => [] ,
  ] ,
  2 => [
    "name" => "addr1" ,
    "type" => "string" ,
    "arguments" => [
      0 => "12"
    ] ,
    "options" => [
      "nullable" => true
    ] ,
  ] ,
  3 => [
    "name" => "addr2" ,
    "type" => "text" ,
    "arguments" => [] ,
    "options" => [
      "nullable" => true
    ] ,
  ]
];

こういうデータから検索を行い、マッチするデータをすべて取得します。

・1. PHPでハッシュの配列から「name が "addr1" のデータ」を取得

$data_selected = array_filter($data, function($hash){
  return ( @$hash['name'] === "addr1" );
});
print_r($data_selected);

・1. 結果

Array
(
    [2] => Array
        (
            [name] => addr1
            [type] => string
            [arguments] => Array
                (
                    [0] => 12
                )

            [options] => Array
                (
                    [nullable] => 1
                )

        )

)

・2. PHPでハッシュの配列から「name が "addr" で始まるデータ( addr1 , addr2 など)」を取得

$data_selected = array_filter($data, function($hash){
  return ( preg_match("/^addr.+/",@$hash['name']) );
});
print_r($data_selected);

・2. 結果

Array
(
    [2] => Array
        (
            [name] => addr1
            [type] => string
            [arguments] => Array
                (
                    [0] => 12
                )

            [options] => Array
                (
                    [nullable] => 1
                )

        )

    [3] => Array
        (
            [name] => addr2
            [type] => text
            [arguments] => Array
                (
                )

            [options] => Array
                (
                    [nullable] => 1
                )

        )

)

・3. PHPでハッシュの配列から「"options" => [ "nullable" => true ] のデータ」を取得

/*
  "options" => [
    "nullable" => true
  ] ,
  のデータを取得
*/
$data_selected = array_filter($data, function($hash){
  return ( @$hash['options']['nullable'] === true );
});
print_r($data_selected);

・3. 結果

Array
(
    [2] => Array
        (
            [name] => addr1
            [type] => string
            [arguments] => Array
                (
                    [0] => 12
                )

            [options] => Array
                (
                    [nullable] => 1
                )

        )

    [3] => Array
        (
            [name] => addr2
            [type] => text
            [arguments] => Array
                (
                )

            [options] => Array
                (
                    [nullable] => 1
                )

        )

)
No.1284
08/06 14:03

edit