我希望创建一个看起来像这样的数组
$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函数创建完美的数组?
答案 0 :(得分:0)
您可以尝试以下代码:
// 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
)
)
)