【问题标题】:Get Array value by string [duplicate]通过字符串获取数组值[重复]
【发布时间】:2021-08-09 14:41:29
【问题描述】:

我有一个数组:

  $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',
    ),
  )
);

..我有一个字符串“files.0.attach”。我如何通过这个字符串从 $ar['files'][0]['attach'] 中获取价值?

按点分解字符串,然后 ....

【问题讨论】:

标签: php arrays string


【解决方案1】:

您与explode 是对的。这是一种获得价值的方法,一次一步:

$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;

这会逐渐向下遍历数组结构,直到到达最后一个分解的索引值。

演示:http://sandbox.onlinephpfunctions.com/code/9dcc22db4ba1795fc9c2b73e12bee250071fed4f

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多