访问内部具有解析的数组中的数组

时间:2018-12-05 14:18:22

标签: php arrays multidimensional-array

我有一个这样的多维数组:

Array
    (
        [0] => Array
            (
                [tag] => EPP
                [type] => open
                [level] => 1
                [attributes] => Array
                    (
                        [XMLNS] => urn:ietf:params:xml:ns:epp-1.0
                    )

                [value] => 

            )


.
.
.

        [35] => Array
            (
                [tag] => DOMAIN:HOSTNAME
                [type] => complete
                [level] => 7
                [value] => ns1.domain.net
            )

.
.
.

        [40] => Array
            (
                [tag] => DOMAIN:HOSTNAME
                [type] => complete
                [level] => 7
                [value] => ns2.domain.net
            )

    )

我想获取内部有value的该数组内所有数组的[tag] => DOMAIN:HOSTNAME键的值。 我尝试使用array_colum($array, 'DOMAIN:HOSTNAME');来执行此操作,该返回一个空数组。我最终希望有一个像这样的数组:

['ns1.domain.net', 'ns2.domain.net']

有什么解决办法吗?

2 个答案:

答案 0 :(得分:1)

array_walk和引用如何?

$hostnames = [];
array_walk($your_array, function($item) use(&$hostnames) {
    if ($item['tag'] == 'DOMAIN:HOSTNAME') {
        $hostnames[] = $item['value'];
    }
});

foreach解决方案:

$hostnames = [];
foreach ($your_array as $item) {
    if ($item['tag'] == 'DOMAIN:HOSTNAME') {
        $hostnames[] = $item['value'];
    }
}

答案 1 :(得分:0)

$array = array(array(
    "tag" => "EPP",
    "type" => "open",
    "level" => "1",
    "attributes"=> 
        array("XMLNS" => "urn:ietf:params:xml:ns:epp-1.0"),
    "value" => "ns1.domain.net"),
    array(
    "tag" => "EPP",
    "type" => "open",
    "level" => "1",
    "attributes"=> 
    array("XMLNS" => "urn:ietf:params:xml:ns:epp-1.0"),
    "value" => "ns2.domain.net"));


foreach($array as $item){
    print $item['value'] . "<br/>";
}

// output
ns1.domain.net
ns2.domain.net

$vals = array();
foreach($array as $value) {
  $vals[] = $value['value'];
}

print_r($vals);
//output 
Array
(
    [0] => ns1.domain.net
    [1] => ns2.domain.net
)