我希望创建一个如下所示的数组
$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函数创建完美的数组?
发布于 2018-06-02 22:37:47
您可以尝试以下代码:
// 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 );
}
}
如果打印出"cart“数组,它将如下所示:
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
)
)
)
https://stackoverflow.com/questions/50640454
复制相似问题