Home > Mobile >  How to get values out of a nested array in PHP
How to get values out of a nested array in PHP

Time:09-22

returning to php after a VERY long break and need some help. So my function is returning the following array. I now want to get the 'id' and 'name' and return them in their own array where name is the key and id is the value. How would I go about it?

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"
      }
    }
  }
}
 

CodePudding user response:

Use array_column() to extract each column, and array_combine() to merge them so one is the key and the other is the value of an associative array.

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

where $object is the variable holding the data you posted.

  • Related