如何访问动态数组键和值

时间:2017-01-14 13:26:50

标签: php

array:1 [▼
 0 => array:4 [▼
   "firstName" => "val"
   "email" => "someval"
   "phone" => "someval"
   "zip" => "someval"
 ]
]

我动态创建了上面的数组。例如firstName,电子邮件字段有时可能会更改4个元素,有时会更改12个元素。不确定如何访问密钥和相应的值。

1 个答案:

答案 0 :(得分:0)

我无法确定数组的哪一部分应该是动态的,但这里有几个例子,我认为可能是你的情况:

  1. 密钥的存在,例如"电子邮件"是动态的,你想找到包含那个键的子数组

    $data = [
        [
            'name' => 'Baz',
            'email' => 'test@example.com',
        ],
        [
            'name' => 'Foo',
        ],
    ];
    
    $dataWithEmail = [];
    foreach ($data as $item) {
        if (array_key_exists('email', $item)) {
            $dataWithEmail[] = $item;
        }
    }
    var_dump($dataWithEmail);
    
    // alternatively you can use:
    
    $dataWithEmail = [];
    $dataWithEmail = array_filter(
        $data,
        function($item) {
            return array_key_exists('email', $item);
        }
    );
    var_dump($dataWithEmail);
    
  2. 数组的深度是动态的,您希望找到"电子邮件"

    $data = [
        [
            [
                [
                    'name' => 'Bar',
                    'email' => 'bar@example.com',
                ],
            ],
        ],
        [
            [
                'name' => 'Foo',
                'email' => 'foo@example.com',
            ],
        ],
    ];
    
    $emails = [];
    array_walk_recursive(
        $data,
        function ($item, $key) use (&$emails) {
            if ('email' === $key) {
                $emails[] = $item;
            }
        }
    );
    var_dump($emails);
    
  3. 您有一个数组,并且您希望将其减少为仅来自键的值(如果存在):

    $data = [
        [
            'name' => 'Baz',
            'email' => 'test@example.com',
        ],
        [
            'name' => 'Foo',
        ],
    ];
    
    $onlyEntriesWithNames = array_filter(
        $data,
        function ($item) {
            return array_key_exists('name', $item);
        }
    );
    $namesFromArray = array_reduce(
        $onlyEntriesWithNames,
        function($carry, $item) {
            $carry[] = $item['name'];
    
            return $carry;
        },
        []
    );
    var_dump($namesFromArray);