0
[items] => stdClass Object
        (
            [1] => stdClass Object
                (
                    [id] => 146300
                    [name]=>aa
                )
            [2] => stdClass Object
                (
                    [id] => 146301
                    [name]=>bb
                )
)
----------------->changing to
[items] => stdClass Object
        (
            [ 146300] => stdClass Object
                (
                    [name] =>aa
                )
            [146301] => stdClass Object
                (
                    [name] => bb
                )
)

how can i do without using foreach. is there any php array function?

Whirlwind
  • 14,286
  • 11
  • 68
  • 157
Ebru
  • 1

1 Answers1

1

Please try this solution:

$result = array();
array_walk($data, function (&$value, &$key) use (&$result) {
    $result[$value->id] = $value;
    unset($result[$value->id]->id);
});
print_r($result);

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

More about array_walk in the documentation

Michal Przybylowicz
  • 1,558
  • 3
  • 16
  • 22
  • This snippet does not respect the top level property `items`. This snippet produces an array of objects, not a three-level object. – mickmackusa Apr 05 '22 at 07:44