使用php从多维数组中获取子数组

Ash*_*mar 3 php extract multidimensional-array sub-array array-key

我想使用 获取多维数组中的值PHP。我将键传递给函数,如果键包含值(即没有任何数组值),它将返回该值。但如果该键包含一个数组值,它将返回整个子数组。

我正在为此添加一个示例数组。

<?php

// prepare a list of array for category, subcategory etc...

$category = array(
'Account' => array(
    'Show Balance' => array(
        'Recharge' => 2300,
        'Success' => 12000,
        'Failure' => 25000,
    ),
    'Balance History' => 'your balance is very low for last 2 years',
    'Mini Statement' => 'This is your mini statement. You can have a look of your transaction details',
    'Last Transaction' => 25000
), 
'Deposit' => array(
    'Deposit Limit' => 40000,
    'Make Deposit' => 'Please go to the nearest branch ans deposit the money.',
    'Last Deposit' => 12000
), 
'FAQ' => array(
    'How To Open An Account' => 'Go to your nearest branch fill up a form, submit it to the branch manger with required supporting documents.',
    'How To Withdraw Money' => 'Go to any ATM center swipe the card enter pin and get your money.',
    'How To Add Money' => 'You need to go to your nearest branch and deposit money over there.'
), 
'Loan' => array(
    'Home Loan' => 'This is home loan related answer',
    'Personal Loan' => 'This is personal loan related answer',
    'Car Loan' => 'This is car loan related answer',
    'Bike Loan' => 'This is bike loan related answer'
) ,
'Test',

);
Run Code Online (Sandbox Code Playgroud)

现在,如果我将数组 $category 和 'Recharge' 作为参数传递给任何PHP函数,它应该返回 2300 作为结果。现在,如果我将数组 $category 和“Show Balance”作为参数传递给任何PHP函数,它应该返回我

array(
        'Recharge' => 2300,
        'Success' => 12000,
        'Failure' => 25000,
    ) 
Run Code Online (Sandbox Code Playgroud)

因此。

在谷歌上搜索了很多但找不到答案。

小智 5

为此编写一个递归函数。执行foreach并使用传递的键检查数组键,如果匹配则返回数组。如果不匹配并检查数组值是否是带有 的数组is_array(),如果是,则再次调用函数,否则返回值

function getData($categoryArray, $key){
    foreach($categoryArray as $k => $value){ 
        if($k==$key) return $value; 
        if(is_array($value)){ 
            $find = getData($value, $key);
            if($find){
                return $find;
            } 
        }
    }
    return null;
}

$result1 = getData($category, 'Show Balance');
var_dump($result1);
$result = getData($category, 'Recharge');
var_dump($result);
Run Code Online (Sandbox Code Playgroud)

演示