首页 > 解决方案 > 如何从PHP中的嵌套数组中获取值

问题描述

经过很长时间的休息后返回 php 并需要一些帮助。所以我的函数返回以下数组。我现在想要获取 'id' 和 'name' 并将它们返回到它们自己的数组中,其中 name 是键,id 是值。我该怎么办?

object(stdClass)#11 (1) {
     ["data"]=>
        array(5) {
    [0]=>
    object(stdClass)#1 (3) {
      ["id"]=>
      string(36) "7fd134a2-5f80-4d07-8a1a-a54c48f7e71b"
      ["type"]=>
      string(13) "userattribute"
      ["attributes"]=>
      object(stdClass)#2 (1) {
        ["name"]=>
        string(10) "Test1Test1"
      }
    }
    [1]=>
    object(stdClass)#3 (3) {
      ["id"]=>
      string(36) "dcdd87d5-1ff3-4fd9-8a75-7e20fe8f19d7"
      ["type"]=>
      string(13) "userattribute"
      ["attributes"]=>
      object(stdClass)#4 (1) {
        ["name"]=>
        string(10) "Test1Test2"
      }
    }
    [2]=>
    object(stdClass)#5 (3) {
      ["id"]=>
      string(36) "b167b703-a63f-4548-9104-43a436871f45"
      ["type"]=>
      string(13) "userattribute"
      ["attributes"]=>
      object(stdClass)#6 (1) {
        ["name"]=>
        string(10) "Test1Test3"
      }
    }
    [3]=>
    object(stdClass)#7 (3) {
      ["id"]=>
      string(36) "6a17046b-b665-493f-83be-35e0a9129c49"
      ["type"]=>
      string(13) "userattribute"
      ["attributes"]=>
      object(stdClass)#8 (1) {
        ["name"]=>
        string(10) "Test1Test4"
      }
    }
    [4]=>
    object(stdClass)#9 (3) {
      ["id"]=>
      string(36) "4704cf6f-1c8b-432e-88df-f6865c8690d5"
      ["type"]=>
      string(13) "userattribute"
      ["attributes"]=>
      object(stdClass)#10 (1) {
        ["name"]=>
        string(10) "Test1Test5"
      }
    }
  }
}
 

标签: phparraysmultidimensional-array

解决方案


用于array_column()提取每一列,array_combine()并将它们合并,因此一个是键,另一个是关联数组的值。

$result = array_combine(array_column($object->data, 'id'), array_column($object->data, 'name'));

$object保存您发布的数据的变量在哪里。


推荐阅读