Home > Net >  PHP - Optional multidimensional keys (differing API objects) [closed]
PHP - Optional multidimensional keys (differing API objects) [closed]

Time:09-17

I am trying to create a function which can process multiple different API requests from different sources dynamically. Some API objects will return the data in different ways, but I want to be able to access the data within the API object by using my $fees array.

Here is my use case:

$fees => Array
(
     [0] => data
     [1] => transaction_config
     [2] => total_fee_amount
)

I want to use this array so that I can access the data from the API Object like so:

$apiObject['data']['transaction_config']['total_fee_amount'];

Some API Objects might only be nested two deep, for example,

$fees => Array
(
     [0] => data
     [1] => fee_total
)

$apiObject['data']['fee_total'];

And I want to be able to dynamically handle this based on the contents of the fees array.

Edit: For better clarification, here is something I have tried which doesn't work

$feeKeys = '';
foreach ($fees as $feeKey) {
    $feeKeys .= "['" . $feeKey . "']";
}
$test = $apiObject . $feeKeys;

Which just returns Array['data']['transaction_config']['total_fee_amount']

Instead of the value

CodePudding user response:

I don't know if I understood you correctly, but what you might find useful is this function:

https://stackoverflow.com/a/36334761/1055314

function flatCall($data_arr, $data_arr_call){
    $current = $data_arr;
    foreach($data_arr_call as $key){
        $current = $current[$key];
    }

    return $current;

The whole code might look like this:

<?php

$fees = [
    0 => 'data',
    1 => 'transaction_config',
    2 => 'total_fee_amount',
];

$apiObject = [
    'data' => [
        'transaction_config' => [
            'total_fee_amount' => 5
        ]
    ]
];

function flatCall($data_arr, $data_arr_call){
    $current = $data_arr;
    foreach($data_arr_call as $key){
        $current = $current[$key];
    }

    return $current;
}

$keys = array_values($fees);

$result = flatCall($apiObject, $keys);

The variable is saved in $result.

Is is what you were looking for?

  • Related