Changing of array format

Hello World,

would like to learn how to change the array format from

     [
(int) 1 => 'Color Red Size 8 - $999.00',
(int) 2 => 'Color Blue Size 9 - $888.00',
(int) 4 => 'Color Red Size 10 - $999.00',
     ]

to this format

    Array
   (
   [0] =>
    (
        [id] => 1
        [name] => Color Red Size 8 - $999.00
     )
    [1] => 
    (
        [id] => 2
        [name] => 'Color Blue Size 9 - $888.00
    )
   [2] => 
    (
        [id] => 4
        [name] => Color Red Size 10 - $999.00',
    )
 )

the reason i would like to do so it because i l want to foreach this array to compare the ID with another table with if statement

            $id = 1

           foreach ($arrays as $object) :
              

                if ($object == $id) {

                    $result = $object;
                }

            endforeach;

can someone quide me how to change it?

thank you very much

:man_bowing:t2:

There are any number of ways to do this. Probably the Hash class has some method that would work.

Personally, I’d use the Cake’s Collection::reduce()

        // untested but should do what you want
        $source =      [
            (int) 1 => 'Color Red Size 8 - $999.00',
            (int) 2 => 'Color Blue Size 9 - $888.00',
            (int) 4 => 'Color Red Size 10 - $999.00',
        ];

        $result = collection($source)
            ->reduce(function($accum, $value, $index) {
                $accum[] = ['id' => $index, 'name' => $value];
                return $accum;
            }, []);

        // or similar but slightly simpler, use the map() method
        $result = collection($source)
            ->map(function($value, $index) {
                return ['id' => $index, 'name' => $value];
            })
            ->toArray();

For more information: Collections - 4.x

Solving a problem like this is really a matter of style.

If you’re not comfortable with using callables yet, you could go super straight-ahead:

        $result = [];
        foreach ($source as $index => $value) {
            $result[] = ['id' => $index, 'name' => $value];
        }

You can see that does essentially what reduce() does.

dear Dreamingmind,

thank you for the suggestions, i give it a try

regards and thank you very much

:man_bowing:t2:

the Cake’s Collection::reduce() is similar Typescript array reduce() , the Cake’s Collection::reduce() function returns the type of array was wanted.

thank you very much

:man_bowing:t2: