php - 如何使用 Push in array 创建完美的数组(woocommerce 重新创建购物车)
问题描述
我正在寻找一个看起来像这样的数组
$cart = array([product_id] array([size], [quantity]));
这是我在页面上的信息:
86253//35//1
86253//36//1
86253//38//2
86253//39//3
86253//40//2
86245//36//7
86245//39//4
$product_id // $size // $quantity
这是我得到它的方法:
foreach($items as $item => $values) {
$_product = wc_get_product( $values['data']->get_id());
if($_product->post_type == 'product_variation'){
echo $_product->parent_id; echo '//'; echo $values['variation']['taille'];
echo '//'; echo $values['quantity'];
}
}
如何使用 push_array php 函数创建完美的数组?
解决方案
您可以尝试以下代码:
// the array to store the data
$cart = array();
foreach($items as $item => $values)
{
$_product = wc_get_product( $values['data']->get_id());
if($_product->post_type == 'product_variation')
{
echo $_product->parent_id; echo '//'; echo $values['variation']['taille'];
echo '//'; echo $values['quantity'];
// create the new temporary array to save the data structure
$tmp = array( $_product->parent_id, array( $values['variation']['taille'], $values['quantity'] ) );
// add the tmp array to the storage array
array_push($cart, $tmp );
}
}
如果您打印出“购物车”数组,它将如下所示:
Array
(
[0] => Array
(
[0] => 86253
[1] => Array
(
[0] => 35
[1] => 1
)
)
[1] => Array
(
[0] => 86253
[1] => Array
(
[0] => 36
[1] => 1
)
)
[2] => Array
(
[0] => 86253
[1] => Array
(
[0] => 38
[1] => 2
)
)
)
编辑:
这不完全是您想要的,但它还应该按产品 ID 对数组数据进行分组:
// the array to store the data
$cart = array();
foreach($items as $item => $values)
{
$_product = wc_get_product( $values['data']->get_id());
if($_product->post_type == 'product_variation')
{
echo $_product->parent_id; echo '//'; echo $values['variation']['taille'];
echo '//'; echo $values['quantity'];
// Check if the parent_id is already set as array key
if( !array_key_exists ( $_product->parent_id, $cart ) )
{
// use the parent_id as key
$cart[$_product->parent_id] = array();
}
// create the new temporary array
$tmp = array( $values['variation']['taille'], $values['quantity'] );
// add the tmp array to the $cart
array_push($cart[$_product->parent_id], $tmp );
}
}
如果你打印出来,它应该是这样的:
Array
(
[86253] => Array
(
[0] => Array
(
[0] => 35
[1] => 1
)
[1] => Array
(
[0] => 36
[1] => 1
)
)
[86245] => Array
(
[0] => Array
(
[0] => 36
[1] => 7
)
[1] => Array
(
[0] => 39
[1] => 4
)
)
)
推荐阅读
- python - 如何修复索引数组中最大值的错误?
- arrays - Kotlin distinct() 来自 2 维数组
- paypal - 如何在 PayPal 确认页面中显示订阅付款?
- visual-studio-code - 如何在 VSCode 中检索活动的 CustomTextEditor
- java - 使用 mockito 和 Junit5 使用参数模拟静态 void 方法
- qt - 需要有关 font.pointSize 和 font.pixelSize 的帮助
- javascript - Firebase 使用 1 个参数调用。预计没有
- excel - 处理前重新格式化 Excel 文档
- mysql - 仅将 MySQL uniq 行增加一个请求
- visual-studio-code - 如何打开这个“控制台”在 VS Code 中安装包?