PHP 获取多维数组中每个键出现的值

问题描述 投票:0回答:3

如何提取键的每个值,无论它在数组中有多深或多浅。

这是一个示例 JSON 数组。我想抓取每一个出现的“内容”并将它们连接成一个字符串。

{
  "foo": [
    "content": "hi",
    "inner": []
  ],
  "bar": [
    "content": "hi2",
    "inner": [
      {
        "bat": [
          "content": "hi3",
          "inner": []
        ],
      }
    ]
  ]
}

理论上,这种情况可以永远持续下去。我们如何获取所有内容值?

php json object multidimensional-array
3个回答
1
投票

我会使用

array_walk_recursive()
,因为它非常简单。

//convert JSON to an array
$data = json_decode($json_data, true);

//create an empty array to hold all of the values we are collecting
$content_values = [];

//this `function` is called for every key in the array that does not contain another array as it's value
//We also pass $content_values as a reference, so we can modify it inside the function
array_walk_recursive($data, function ($value, $key) use (&$content_values) {
    if ($key === 'content') {
        $content_values[] = $value;
    }
});

//Lastly, implode all of the array elements into a string with the given separator
$concatenated_content = implode(', ', $content_values);
echo $concatenated_content;

输出

hi, hi2, hi3

1
投票

您必须创建一个函数来获取数组值。它将检查每个数组元素。如果数组元素是一个数组,那么它将再次调用自身,否则该值将存储在另一个数组中。

新数组将是预期的结果。对于数组的任何维度,它都可以工作。

function extractKeyValues($data, $key)
{
    $values = [];

    foreach ($data as $element) {
        if (is_array($element)) {
            $values = array_merge($values, extractKeyValues($element, $key));
        } elseif (is_string($element) && $key === 'content') {
            $values[] = $element;
        }
    }

    return $values;
}

$jsonData = '{
    "foo": [
        {
            "content": "hi",
            "inner": []
        }
    ],
    "bar": [
        {
            "content": "hi2",
            "inner": [
                {
                    "bat": [
                        {
                            "content": "hi3",
                            "inner": []
                        }
                    ]
                }
            ]
        }
    ]
}';

$dataArray = json_decode($jsonData, true);
$contentValues = extractKeyValues($dataArray, 'content');

$result = implode(' ', $contentValues);

0
投票

给你:

输入:

$array = [
    "foo" => [
        "content" => "hi",
        "inner" => []
    ],
    "bar" => [
        "content" => "hi2",
        "inner" => [
            "bat" => [
              "content" => "hi3",
              "inner" => []
            ]
        ]
    ],
    "biz" => [
        "content" => "hi4",
        "inner" => [
            "bat" => [
              "content" => "hi5",
              "inner" => [
                    "bong" => [
                        "content" => "bong",
                        "inner" => [
                            "bat" => [
                              "content" => "bong0",
                              "inner" => []
                            ]
                        ]
                    ],
                    "bong1" => [
                        "content" => "bong1",
                        "inner" => [
                            "bong2" => [
                              "content" => "bong2",
                              "inner" => []
                            ]
                        ]
                    ]
              ]
            ]
        ]
    ]
];

递归函数

    function getContent($array){
        
        $content = [];
        
        foreach($array as $row){
            foreach($row as $key => $value){
                switch($key){
                    case 'content':
                        $content[] = $value;
                    break;
                    case 'inner':
                        $content = array_merge($content, getContent($value)); //recurse
                    break;
                }
            }
        }

        return $content;
    }
    
    print_r( getContent($array) );
    

结果

Array
(
    [0] => hi
    [1] => hi2
    [2] => hi3
    [3] => hi4
    [4] => hi5
    [5] => bong
    [6] => bong0
    [7] => bong1
    [8] => bong2
)

您可以使用“内爆”和任何您喜欢的分隔符。我更喜欢构建一个数组,然后将其内爆。

© www.soinside.com 2019 - 2024. All rights reserved.