【发布时间】:2021-09-21 16:34:10
【问题描述】:
在很长一段时间后返回 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"
}
}
}
}
【问题讨论】:
-
这不是一个数组,它是一个对象。
$object->data是一个数组。 -
我实际上最终通过使用以下结果的变体来解决它!所以因为 ID 嵌套在属性中,所以我最终使用了以下代码: $attribute_names = array_column($obj->data, 'attributes'); $result = array_combine(array_column($attribute_names, 'name'),array_column($obj->data, 'id'));
-
您应该将其发布为答案,而不是接受我的答案。我没有注意到额外的嵌套级别。
标签: php arrays multidimensional-array