Skip to content
Advertisement

Renaming an object key with a property of it’s own in PHP

I have an object like this in PHP-

array(2) {
  [0]=>
  object(stdClass)#1869 (10) {
    ["id"]=>
    string(1) "1"
    ["country"]=>
    string(7) "Austria"
    ["cat_one"]=>
    string(7) "#FFCB69"
  }
  [1]=>
  object(stdClass)#1868 (10) {
    ["id"]=>
    string(1) "2"
    ["country"]=>
    string(7) "Belgium"
    ["cat_one"]=>
    string(7) "#FFCB69"
  }
}

I would like to take the country property and set it as the key of each values in the root object. A foreach resets the whole object value on each keys. Intended result is similar to the one right below –

array(2) {
  [Austria]=>
  object(stdClass)#1869 (10) {
    ["id"]=>
    string(1) "1"
    ["cat_one"]=>
    string(7) "#FFCB69"
  }
  [Belgium]=>
  object(stdClass)#1868 (10) {
    ["id"]=>
    string(1) "2"
    ["cat_one"]=>
    string(7) "#FFCB69"
  }
}

Advertisement

Answer

As array_column can extract public property from objects, which are elements of arrays, you can:

$array = []; // your initial array
print_r(
    array_combine(
        // extract country property from each object
        array_column($array, 'country'), 
        $array
    )
);

But this method does not remove country property from each object.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement