从之前的Foreach调用结果

时间:2016-02-26 20:46:01

标签: php foreach woocommerce

我试图通过另一个回声方式从我的Foreach获得结果,然后是foreach,但是我被卡住了,任何帮助都会很多。

$items = $order->get_items();

// Output the loop
foreach ($order->get_items() as $item) {
    // Getting some information
    $product_qty = $item['qty'];
$product_variation_id = $item['variation_id'];
    $product = new WC_Product($item['product_id']);

    // SKU
    $SKU = $product->get_sku();
    print_r($SKU); 
    print_r($product_qty); 
    print_r(' ');
}
// this gives all 3 quantities and all 3 sku, added a space at the end for easier reading

// this only gives the 1st entry of both variables but i need all 3 of both variables 
echo '<a href="https://www.domainname.someurl'.$product_quantity .$SKU . '" target=_blank>'; 

echo "<p>TEXT</p></a>";

我希望这样清楚,谢谢

3 个答案:

答案 0 :(得分:0)

尝试以下代码

$items = $order->get_items();
// Output the loop
$product_qty_string = '';
$sku_string = '';
foreach ($order->get_items() as $item) {
    // Getting some information
    $product_qty_string .= $item['qty']."-";
    // SKU
    $SKU = $product->get_sku();
    $sku_string .=$SKU."-";
}

$product_quantity = rtrim($product_qty_string,'-');
$SKU = rtrim($sku_string,'-');
echo '<a href="https://www.domainname.someurl'.$product_quantity.''.$SKU.''" target=_blank>';

echo "<p>TEXT</p></a>";

答案 1 :(得分:0)

为什么不在数组中添加值,然后将它们内爆。

$items = $order->get_items();

// Output the loop
$SKU = $product_qty = [];
foreach ($order->get_items() as $item) {
    // Getting some information
    $product_qty[] = $item['qty'];
    $product_variation_id = $item['variation_id'];
    $product = new WC_Product($item['product_id']);

    // SKU
    $SKU[] = $product->get_sku();
    print_r($SKU); 
    print_r($product_qty); 
    print_r('&nbsp;');
}
$sku_string = implode('-', $SKU);
$product_qty_string = implode('-', $product_qty);

echo '<a href="https://www.domainname.someurl'.$product_qty_string .$sku_string . '" target=_blank>'; 

echo "<p>TEXT</p></a>";

您可以使用您想要的任何分隔符内嵌您的数据,我使用&#34; - &#34;对于我的例子,但它取决于你的需要。

答案 2 :(得分:0)

好吧,你在每次迭代时都会覆盖$ SKU和product_qty的值,也许尝试将它们存储在一个数组中?就像在场外创建一个数组循环并使用array_push(created_array,array($ SKU,$ product_qty))。希望它有所帮助。

$items = $order->get_items();
$push = array();
// Output the loop
foreach ($order->get_items() as $item) {
// Getting some information
  $product_qty = $item['qty'];
  $product_variation_id = $item['variation_id'];
  $product = new WC_Product($item['product_id']);

  // SKU
  $SKU = $product->get_sku();

  array_push($push, array('sku'=>$SKU, 'qty'=>$product_qty));
  print_r($SKU); 
  print_r($product_qty); 
  print_r('&nbsp;');
}
// this gives all 3 quantities and all 3 sku, added a space at the end for easier reading

// this only gives the 1st entry of both variables but i need all 3 of both variables

$link = '<a href="https://www.domainname.someurl';
for ($i=0;$i<count($push);$i++){
        $link .= $push[$i]['qty'];
        $link .= $push[$i]['sku'];
    }
    $link .= '" target=_blank>';
 echo $link;