0

I have an array:

  $ar = array(
'color' => '4',
  'files' => 
  array (
    0 => 
    array (
      'id' => '481',
      'this' => '154',
      'format' => '23',
      'attach' => '64a73c4aa9c3409f230e54b283baa221.webp',
    ),
    1 => 
    array (
      'id' => '482',
      'this' => '154',
      'format' => '22',
      'attach' => '54afc3dce6cd36c763844d9a3e4a3639.webp',
    ),
    2 => 
    array (
      'id' => '483',
      'this' => '154',
      'format' => '23',
      'attach' => 'e83f3103b7f25d52262330a4b5652401.webp',
    ),
  )
);

..and i have a string "files.0.attach". How i can get value from $ar['files'][0]['attach'] by this string?

Explode the string by dot, and ....

Tarya
  • 3
  • 1
  • 1
    Does this answer your question? [How to access and manipulate multi-dimensional array by key names / path?](https://stackoverflow.com/questions/27929875/how-to-access-and-manipulate-multi-dimensional-array-by-key-names-path) – El_Vanja May 20 '21 at 10:45

1 Answers1

0

You are on the right lines with explode. Here's a way to get to the value, one step at at time:

$ar = array(
'color' => '4',
  'files' => 
  array (
    0 => 
    array (
      'id' => '481',
      'this' => '154',
      'format' => '23',
      'attach' => '64a73c4aa9c3409f230e54b283baa221.webp',
    ),
    1 => 
    array (
      'id' => '482',
      'this' => '154',
      'format' => '22',
      'attach' => '54afc3dce6cd36c763844d9a3e4a3639.webp',
    ),
    2 => 
    array (
      'id' => '483',
      'this' => '154',
      'format' => '23',
      'attach' => 'e83f3103b7f25d52262330a4b5652401.webp',
    ),
  )
);

$str = "files.0.attach";
$indexes = explode(".", $str);
$obj = $ar;

foreach ($indexes as $i)
{
    $obj = $obj[$i];
}

echo $obj;

This gradually traverses down the array structure, until it reaches the last exploded index value.

Demo: http://sandbox.onlinephpfunctions.com/code/9dcc22db4ba1795fc9c2b73e12bee250071fed4f

ADyson
  • 57,178
  • 14
  • 51
  • 63