2016-06-10 3 views
0

Я работаю над проектом cakephp, где я должен создавать отчеты. У меня две таблицы, одна таблица хранит значение клиента, а другая таблица хранит значение отведений, назначенных каждому пользователю. Каждый свинец имеет статус. Я хочу, чтобы увеличить счетчик progressleads если состояние 0, если состояние 1, то счетчик wonleads следует увеличивать и так далее ...increment counter status wise in php foreach

Я присоединяюсь две таблицы и получить массив как этот =>

Array 
(
    [0] => Array 
     (
      [Customer] => Array 
       (
        [id] => 14 
        [name] => ABC 
       ) 

      [Opportunity] => Array 
       (
        [status] => 0 
        [value] => 50000 
       ) 

     ) 

    [1] => Array 
     (
      [Customer] => Array 
       (
        [id] => 14 
        [name] => ABC 
       ) 

      [Opportunity] => Array 
       (
        [status] => 1 
        [value] => 10000 
       ) 

     ) 

    [2] => Array 
     (
      [Customer] => Array 
       (
        [id] => 14 
        [name] => ABC 
       ) 

      [Opportunity] => Array 
       (
        [status] => 1 
        [value] => 7500 
       ) 

     ) 

    [3] => Array 
     (
      [Customer] => Array 
       (
        [id] => 15 
        [name] => DEF 
       ) 

      [Opportunity] => Array 
       (
        [status] => 0 
        [value] => 45000 
       ) 

     ) 

    [4] => Array 
     (
      [Customer] => Array 
       (
        [id] => 19 
        [name] => ST 
       ) 

      [Opportunity] => Array 
       (
        [status] => 2 
        [value] => 50000 
       ) 

     ) 

    [5] => Array 
     (
      [Customer] => Array 
       (
        [id] => 16 
        [name] => TEST 
       ) 

      [Opportunity] => Array 
       (
        [status] => 2 
        [value] => 1000000 
       ) 

     ) 

    [6] => Array 
     (
      [Customer] => Array 
       (
        [id] => 19 
        [name] => ST 
       ) 

      [Opportunity] => Array 
       (
        [status] => 0 
        [value] => 1000 
       ) 

     ) 

    [7] => Array 
     (
      [Customer] => Array 
       (
        [id] => 14 
        [name] => ABC 
       ) 

      [Opportunity] => Array 
       (
        [status] => 0 
        [value] => 
       ) 

     ) 

) 

Из этого массива я хочу одну запись для каждого пользователя с общими выводами, inprogress ведет, выиграл счетчик счетчиков. Я попытался следующим кодом: -

$customerdetails = array(); 
      $totalopp = 0; 
      $progressopp = 0; 
      $oppval = 0; 
      $wonopp = 0; 
      $lostopp = 0; 
      $billedopp = 0; 
      $onholdopp = 0; 
      $newcustid = NULL; 
      foreach($customer as $k => $val){ 
       $custid = $val["Customer"]["id"]; 
       if($newcustid != $custid){ 
        $oppstatus = $val["Opportunity"]["status"]; 
        $oppval += $val["Opportunity"]["opo_value"]; 
        $totalopp++; 
        if($oppstatus == 0){ 
         $progressopp++; 
        } 
        if($oppstatus == 1){ 
         $wonopp++; 
        } 
        if($oppstatus == 2){ 
         $lostopp++; 
        } 
        if($oppstatus == 3){ 
         $billedopp++; 
        } 
        if($oppstatus == 4){ 
         $onholdopp++; 
        } 
        $newcustid = $custid; 
       } 
        $customerdetails[$custid]["customername"] = $val["Customer"]["customer_name"]; 
        $customerdetails[$custid]["opportunities"] = $totalopp; 
        $customerdetails[$custid]["value"] = $oppval; 
        $customerdetails[$custid]["inprogress"] = $progressopp; 
        $customerdetails[$custid]["won"] = $wonopp; 
        $customerdetails[$custid]["lost"] = $lostopp; 
        $customerdetails[$custid]["billed"] = $billedopp; 
        $customerdetails[$custid]["onhold"] = $onholdopp; 

      } 

После печати $ customerdetails массива я получаю следующие результаты =>

Array 
(
    [14] => Array 
     (
      [customername] => ABC 
      [opportunities] => 6 
      [value] => 1146000 
      [inprogress] => 4 
      [won] => 0 
      [lost] => 2 
      [billed] => 0 
      [onhold] => 0 
     ) 

    [15] => Array 
     (
      [customername] => DEF 
      [opportunities] => 2 
      [value] => 95000 
      [inprogress] => 2 
      [won] => 0 
      [lost] => 0 
      [billed] => 0 
      [onhold] => 0 
     ) 

    [19] => Array 
     (
      [customername] => ST 
      [opportunities] => 5 
      [value] => 1146000 
      [inprogress] => 3 
      [won] => 0 
      [lost] => 2 
      [billed] => 0 
      [onhold] => 0 
     ) 

    [16] => Array 
     (
      [customername] => TEST 
      [opportunities] => 4 
      [value] => 1145000 
      [inprogress] => 2 
      [won] => 0 
      [lost] => 2 
      [billed] => 0 
      [onhold] => 0 
     ) 

) 

Как вы можете видеть, что есть только 4 провода, присвоенный ABC, но он показывает возможности как 6 аналогично, другие счетчики также отображаются некорректно. Может ли кто-нибудь помочь мне, что я делаю неправильно здесь?

ответ

1

Я думаю, что вы применяете неверную логику здесь. array_column будет делать трюк. См. Следующий код.

<?php 

$customers=array_column($result,'customer'); 
$opportunity=array_column($result,'opportunity'); 

$finalResult=array(); 

foreach($customers as $k=>$customer) { 
    $opp=$opportunity[$k]; 
    if(!array_key_exists($customer["id"],$finalResult)) { 
     $finalResult[$customer["id"]]=array(); 
     $finalResult[$customer["id"]]["opportunities"]=0; 
     $finalResult[$customer["id"]]["value"]=0; 
     $finalResult[$customer["id"]]["inprogress"]=0; 
     $finalResult[$customer["id"]]["won"]=0; 
     $finalResult[$customer["id"]]["lost"]=0; 
     $finalResult[$customer["id"]]["billed"]=0; 
     $finalResult[$customer["id"]]["onhold"]=0; 
    } 
    $finalResult[$customer["id"]]["customerid"]=$customer["id"]; 
    $finalResult[$customer["id"]]["customername"]=$customer["name"]; 
     $finalResult[$customer["id"]]["opportunities"]++; 
     $finalResult[$customer["id"]]["value"]+=$opp["value"]; 
     if($opp["status"]==0) { 
      $finalResult[$customer["id"]]["inprogress"]++; 
     } 
     if($opp["status"]==1) { 
      $finalResult[$customer["id"]]["won"]++; 
     } 
     if($opp["status"]==2) { 
      $finalResult[$customer["id"]]["lost"]++; 
     } 
     if($opp["status"]==3) { 
      $finalResult[$customer["id"]]["billed"]++; 
     } 
     if($opp["status"]==4) { 
      $finalResult[$customer["id"]]["onhold"]++; 
     }  
} 

?> 

Вам просто нужно получить столбец столбца клиента и столбец возможностей отдельно, а затем пройти колонку клиентов.

Теперь, когда вы проходите, сначала проверьте, не нашли ли вы этого клиента или нет, сохраняя значения в массиве $finalResult. Если да, то просто увеличивайте счетчики соответственно, если не создайте массив, а затем соответственно увеличите счетчик.

Я думаю, что это сделает трюк.

Выходной массив может выглядеть следующим образом:

Array 
(
    [14] => Array 
     (
      [opportunities] => 4 
      [value] => 13500 
      [inprogress] => 2 
      [won] => 2 
      [lost] => 0 
      [billed] => 0 
      [onhold] => 0 
      [customerid] => 14 
      [customername] => ABC 
     ) 

    [15] => Array 
     (
      [opportunities] => 1 
      [value] => 45000 
      [inprogress] => 1 
      [won] => 0 
      [lost] => 0 
      [billed] => 0 
      [onhold] => 0 
      [customerid] => 15 
      [customername] => DEF 
     ) 

    [19] => Array 
     (
      [opportunities] => 2 
      [value] => 51000 
      [inprogress] => 1 
      [won] => 0 
      [lost] => 1 
      [billed] => 0 
      [onhold] => 0 
      [customerid] => 19 
      [customername] => ST 
     ) 

    [16] => Array 
     (
      [opportunities] => 1 
      [value] => 100000 
      [inprogress] => 0 
      [won] => 0 
      [lost] => 1 
      [billed] => 0 
      [onhold] => 0 
      [customerid] => 16 
      [customername] => TEST 
     ) 

) 
+0

Спасибо за вашу помощь, но вы можете рассказать мне, что такое $ result contains? – user3327608

+0

'$ finalResult' - это просто массив, который будет содержать окончательный результат. Проверьте обновленный ответ для формата массива. –

+0

Это первая запись, которую я получил, как это: - Массив ( [14] => Массив ( [возможности] => 1 [значение] => 50000 [InProgress] => 1 [выиграл] => 0 [потерял] => 0 [счет] => 0 [onhold] => 0 [CustomerID] => 14 [CustomerName] => ABC ) – user3327608

0

Что ваша логика делает это:

if($newcustid != $custid){ 
    $totalopp++; 
} 

И назначая $ newcustid к нулю. Я думаю, что это условие приведет вас к неправильным возможностям.

+0

Когда оба не то же самое в то время я для увеличения значения счетчика. Я хочу, чтобы значения счетчика учитывались для каждого пользователя. Я новичок в php. Пожалуйста, помогите мне – user3327608