Home > Back-end >  Get value of dynamic sub-array, in multidimensional array
Get value of dynamic sub-array, in multidimensional array

Time:03-25

Not sure if my question is clear, but here's what I'm trying to achieve. Let’s say I have a multidimensional array like so:

$arr['client1']**['dog']['Jack']**
$arr['client2']['cat']['Stacy']

How can I get the second portion of the array (between **), knowing it can be anything. For client 3, it could be a crocodile. For Client 4, it could be a car.

So I'm looking to "build" the structure of the array, dynamically. Something like so:

$arr['client1']{partBetweenThe**InTheExemple}

{partBetweenThe**InTheExemple} would be constructed "on the fly" (hence, the dynamically).

EDIT: Hopefully some clarifications...

The array changes every time. Basically, I'm building an addon to poll any API on the web. The data structure I'm getting can be anything. So what I need to do is build the key combination "on the fly", with variables.

In the exemple above, my variable would be something like $query = ['dog']['Jack'] and to get the value, I would poll it like so (from a logistic perspective, I know this doesn't work):

$arr['client1'][$query] or $arr['client1']$query or $arr['client1']{$query}

CodePudding user response:

You can define the query as an array with each level as an element. Then we can iterate through that and check if we find a matching key in the response:

function findInArray(array $query, array $data)
{
    foreach ($query as $key) {
        if (!array_key_exists($key, $data)) {
            // The key was not found, abort and return null
            return null;
        }

        // Since the key was found, move to next level
        $data =& $data[$key];
    }
    
    return $data;
}

// Example response
$response = [
    'client1' => [
        'dog' => [
            'Jack' => 'Some value',
        ],
    ]
];

// Define the query as an array
$query = ['dog', 'Jack'];

$result = findInArray($query, $response['client1']);

Demo: https://3v4l.org/WjXTn

CodePudding user response:

Edit:

So since the array's structure can't be changed this will return the client if the structure remains ['client']['animal']['name'].

$clients = [
    'client1' => [
        'dog' => [
            'Jack' => []
        ]
    ],
    'client2' => [
        'cat' => [
            'Stacy' => []
        ]
    ]
];

$animal = 'dog';
$name = 'Jack';

foreach ($clients as $client => $options) {
    if (
        array_key_exists($animal, $options) &&
        array_key_exists($name, $options[$animal])
    ) {
        echo $client;
        break;
    }
}
  • Related