skip to Main Content

I have arrays like this

$InternetGatewayDevice[‘DeviceInfo’][0][‘SoftwareVersion’][1][‘_value’]

and also like this

$InternetGatewayDevice[‘DeviceInfo’][1][‘SoftwareVersion’][2][‘_value’]

actually, both of them return same value, which is the software version for the router, but because routers belong to different vendors, I have that problem, so
actually, I want to know the path that I have to go in, in order to get my value
so I want to have somethings like this

InternetGatewayDevice.DeviceInfo.0.SoftwareVersion.1._value

as a string
I mean I want a function where I can provide to it the array and the key ,so the function will return to me the path of the array that I have to follow in order to get the value like this

getpath($array,"SoftwareVersion")

whhich will return value like this

InternetGatewayDevice.DeviceInfo.0.SoftwareVersion

are there any way to do this in php ?or laravel package
or is there any way in PHP to get the value whatever the number key is?
I mean like this

$InternetGatewayDevice['DeviceInfo'][*]['SoftwareVersion'][*]

so what ever the key it will return the value

2

Answers


  1. you can use the get function from lodash php
    https://github.com/lodash-php/lodash-php

    Example:

    <?php
     use function _get;
    
    $sampleArray = ["key1" => ["key2" => ["key3" => "val1", "key4" => ""]]];
    get($sampleArray, 'key1.key2.key3');
    // => "val1"
    
    get($sampleArray, 'key1.key2.key5', "default");
    // => "default"
    
    get($sampleArray, 'key1.key2.key4', "default");
    // => ""
    
    Login or Signup to reply.
  2. You could try to use he data_get helper function provided by Laravel.

    public function getSoftwareVersion(array $data, int $deviceInfoIndex, int $softwareVersionIndex)
    {
        $index = "DeviceInfo.{$deviceInfoIndex}.SoftwareVersion.{$softwareVersionIndex}";
    
        return data_get($data, $index);
    }
    

    Then it can be used like

    $softwareVersion = getSoftwareVersion($internetGatewayDevice, 1, 0);
    

    Laravel Docs – Helpers – Method data_get

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search