PHP-在函数内部创建多维数组


PHP - create multidimensional array inside function

我想在函数内部创建多维数组,然后在函数外部访问它。现在我有这个功能:

function custom_shop_array_create($product, $counter){
    $product_id = get_the_ID();
    $product_title = get_the_title($product_id);
    $products_arr[]['id'] = $product_id;
    $products_arr[]['title'] = $product_title;
    $products_arr[]['price'] = $product->get_price();
    $products_arr[]['image'] = get_the_post_thumbnail($product_id, 'product-list-thumb', array('class' => 'product-thumbnail', 'title' => $product_title));
    return $products_arr;
}

它在这个代码中被称为:

$products_arr = array();
    if ( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post();
        custom_shop_array_create($product);
    endwhile;
    endif;

问题是我不能访问CCD_ 1。我试过用$my_array[] = custom_shop_array_create($product);替换custom_shop_array_create($product);,但后来得到了三维数组。有没有什么方法可以得到这样的二维阵列:

product 1 (id,title,price,image)
product 2 (id,title,price,image) etc.

功能之外。

感谢转发

当然。让函数返回最终数组的,并自己进行附加:

function custom_shop_array_create($product, $counter){
    $product_id = get_the_ID();
    $product_title = get_the_title($product_id);
    return [
        'id' => $product_id,
        'title' => $product_title,
        // etc
    ];
}

然后:

$products_arr = array();
if ( $products->have_posts() ) :
    while ( $products->have_posts() ) : 
        $products->the_post();
        $products_arr[] = custom_shop_array_create($product);
    endwhile;
endif;

也就是说,while循环中发生了一些奇怪的事情。$products->the_post()做什么?$product从哪里来?