2

Following is my array

(
    [0] => Array
        (
            [items] => 10.4
            [Total] => 10.4
        )

    [1] => Array
        (
            [items] => 10.5
            [Total] => 10.5
        )

    [2] => Array
        (
            [items] => 4.5
            [Total] => 15
        )

    [3] => Array
        (
            [items] => 15.2
            [Total] => 15.2
        )

    [4] => Array
        (
            [items] => 8.4
            [Total] => 8.4
        )

)

Here each array has items & total , I want to check if total of each item is less then 20 then set items with total in a array and also not check already checked item.

For example there are 4 items in array 0 has item 10.4 & total 10.4 then check is less then 20 if not then plus second array item means (10.4 + 10.5) again check if is greater then 20 If yes then set last checked in array like array('item'=>10.4, 'total'=>10.4) , Now second time 10.4 item will skip & check with 10.5 + 4.5 etc...

I want output like.

(
[0] => Array
    (
        [items] =>  array([0]=>10.4),
        [Total] => 10.4
    )

[1] => Array
    (
        [items] => array(
            [0] => 10.5,
            [1] => 4.5   
        ),         
        [Total] => 15
    )

[2] => Array
    (
        [items] => array([0]=>15.2)            
        [Total] => 15.2
    )

[3] => Array
    (
        [items] => array([0]=>8.4)            
        [Total] => 8.4
    )

) Following is my script.

$packageInfo = $ordercon->get_package_items_by_order_number($order_number); // Comes from model

// First calculate the total
foreach ($packageInfo as $key => $package) {
    $packageInfo[$key]['total_weight'] = $package['quantity'] * $package['weight'];
    $packageInfo[$key]['currnt_item'] = $package['quantity'] * $package['weight'];

}


// Then check count the packages ?
$packages = [];
$packageTotalWeight = 0;
$packageItemWeight = 0;

foreach ($packageInfo as $key => $package) {

    if(($packageTotalWeight + $package['total_weight']) > 20){
        $packages[]['final_total'] = $packageTotalWeight;
        $packageTotalWeight = $package['total_weight'];
       $data[] = array('items'=>$package['currnt_item'], 'Total'=>$packageTotalWeight);  // For combine items       
    } else {
        $packages[]['currntItem'] = $package['quantity'] * $package['weight'];
        $packageTotalWeight += $package['total_weight'];
        $data[] = array('items'=>$package['currnt_item'], 'Total'=>$packageTotalWeight);           
    }
}


echo "<pre>";print_r($data);
echo '<pre>packageInfo';print_r($packageInfo);
David
  • 223
  • 1
  • 3
  • 9
  • You can't have an associative array with 2 identical keys (`items` in element 0 of your desired output). You will need to have a third level of array i.e. `items => array(10.5, 4.5)` – Nick Dec 18 '19 at 06:03
  • @Nick , Can you please help me for this ? I don't have any idea about it. – David Dec 18 '19 at 06:06

0 Answers0