PHP. Как использовать foreach внутри массива?

Рейтинг: 0Ответов: 1Опубликовано: 25.03.2023

Хочу реализовать такой код

$result = [
'id' => '1',
'result' => [
    'test1' => true,
    'test2' => {
        'test' => [
            foreach(WC() - > cart - > get_cart() as $cart_item) {
                $product = $cart_item['data'];
                if (!empty($product)) {
                    echo {
                        'id' => $product - > id
                    },

                }
            }
        ]
    }


]

]

result должен быть таким

[
'id' => '1',
'result' => [
    'test1' => true,
    'test2' => {
        'test' => [
           {
                'id' => 1,
            },
            {
                'id' => 2,
            },
            {
                'id' => 3,
            },
            {
                'id' => 4,
            },

        ]
    }


]

]

Заранее спасибо

Ответы

▲ 0
$test = [];

foreach ( WC()->cart->get_cart() as $cart_item ) {
    $product = $cart_item['data'];

    if ( ! empty( $product ) ) {
        $test[] = [ 'id' => $product->id ];
    }
}

$result = [
    'id'     => '1',
    'result' => [
        'test1' => true,
        'test2' => [ 'test' => $test ],
    ],
];