Compare two PHP objects

0

I have a problem, I am currently trying to compare two objects, one object is cash sales and the other is card sales.

  

Cash sales

[
  {
    "ventas": 1,
    "dia": 7,
    "total": 120
  },
  {
    "ventas": 1,
    "dia": 8,
    "total": 100
  }
]
  

Sales with card

[
  {
    "ventas": 3,
    "dia": 8,
    "total": 360
  }
]

But for daily reports using ChartJs I try to get this structure:

  

Cash sales

[1, 1]
  

Sales with card

[0, 3]

For that I try to perform with a foreach

foreach ($ventasEfectivo as $keyEfecitvo => $efectivo) {
       $contado[] = $efectivo->ventas;
       foreach ($ventasTarjeta as $keyCredito => $credito) {
           if ($keyEfecitvo == $keyCredito) {
               $credito[] = $credito->ventas;
           }elseif(isset($keyCredito)){
               $credito[] = 0;
           }
       }
}

But this brings me back:

[3,0]

Instead of

[0, 3]
    
asked by Carlos Mendez 08.09.2018 в 18:49
source

1 answer

2

I think this could help. We use a variable autoincremental to compare the day and be able to get the complete array with every day:

function count_ventas($ventasEfectivo, $ventasTarjeta, $cantidad){
    for($i = 1; $i <= $cantidad; $i++){
        foreach($ventasEfectivo as $venta){
            if($i == $venta['dia']){
                $ventas['contado'][$i] = $venta['ventas'];
            }
            if(!isset($ventas['contado'][$i])){
                $ventas['contado'][$i] = 0;
            }
        }
        foreach($ventasTarjeta as $keyCredito => $credito){
            if ($i == $credito['dia']){
                $ventas['creditos'][$i] = $credito['ventas'];
            }
            if(!isset($ventas['creditos'][$i])){
                $ventas['creditos'][$i] = 0;
            }
        }
    }
    return $ventas;
}

print_r(count_ventas($ventasEfectivo, $ventasTarjeta, 8));
//Array ( [contado] => Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 1 [8] => 3 ) [creditos] => Array ( [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 3 ) )

I could not check the operation because I'm on the phone, but I think the logic is correct.

Greetings!

    
answered by 08.09.2018 в 19:07