2016-03-30 2 views
0

У меня есть трудный треск.сочетать одинаковые значения в php-массивах

У меня есть этот массив писем:

Array ( 
[0] => [email protected] 
[1] => [email protected] 
[2] => [email protected] 
[3] => [email protected] 
[4] => [email protected] 
[5] => [email protected] 
[6] => [email protected] 
) 

И этот массив форм идентификаторов:

Array ( 
[0] => 1a21f6b7-8025-4724-b983-14745823ede1 
[1] => 4c8a63c0-4650-4884-b83c-70054f538ec2 
[2] => 148c1886-6674-45f3-9665-748bb6a34f4c 
[3] => 02fc3795-9457-4b02-91da-7d4b63eac1c0 
) 

И с этим Еогеаспом я бег через каждую почту в массиве, чтобы создать полный JSON Объект

foreach($mails_array as $key => $value) { 

    foreach($formIds as $form) { 

     $branchArray = array(
        "FormIds" => [''.$form.''], 
        "Conditions" => array("sendto" => $value), 
        "From" => $date_from, 
        "To" => $date_to, 
        "Days" => '' 
       ); 

     array_push($array, $branchArray); 
    } 
} 

$json = json_encode($array); 
$string = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $json); 

Это создает этот json, который используется для вызова API для возврата количества подпрограмм сии на X формах, основанные на состоянии (SENDTO):

[{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["1a21f6b7-8025-4724-b983-14745823ede1"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["4c8a63c0-4650-4884-b83c-70054f538ec2"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["148c1886-6674-45f3-9665-748bb6a34f4c"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""},{FormIds:["02fc3795-9457-4b02-91da-7d4b63eac1c0"],Conditions:{sendto:"[email protected]"},From:"2016-03-23",To:"today",Days:""}] 

Где FormIds является GUID конкретной формы с представлением. «sendto» в условиях - это почта, которую я хочу, чтобы все материалы были представлены в конкретной форме.

Так как пример я пытаюсь получить все представления на всех 4-х формах, которые посылают в [email protected]

Приведенные выше JSon возвращает это, где это число представлений о состоянии:

{ 
    "arr": [ 
    1, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    1, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0, 
    0 
    ] 
} 

Так что я знаю, что первые 4 элемента (4 формы) в возвращенном JSON для [email protected] (1,0,0,0), следующие 4 для [email protected] (0 , 0,0,0) и т. Д.

Теперь моя проблема заключается в том, что я хочу объединить массив почты и возвращенный json в простой json, который я могу вывести с адресом электронной почты и количеством полных представлений. 4 формы с одинаковым «sendto» должны быть объединены, так что условие с [email protected], которое находится на 4 формах, будет объединено в один элемент с общим количеством представлений в 4 формах.

Что-то вроде:

{"landingPageData":[{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":"1"}},{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":0}},{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":"1"}},{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":"0"}},{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":"0"}},{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":"-"}},{"landingPage":{"landingPageMail":"[email protected]","landingPageLeads":"0"}}],"totalLeads":2})

ответ

1

Вы можете перебирать $mails_array и просуммировать подытоги с помощью array_sum(array_slice()):

$json = '{"arr":[1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}'; 

$data = json_decode($json)->arr; 
$result = array('landingPageData'=>[], 'totalLeads'=>0); 

foreach($mails_array as $key => $email) 
{ 
    $subTot = array_sum(array_slice($data,$key*count($formIds), count($formIds))); 
    $result['landingPageData'][] = array 
    (
     'landingPage' => array 
     (
      'landingPageMail' => $email, 
      'landingPageLeads' => $subTot 
     ) 

    ); 
    $result['totalLeads'] += $subTot; 
} 

$result = json_encode($result); 

echo $result; 

напечатает (prettified):

{ 
    "landingPageData": [ 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 1 
      } 
     }, 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 0 
      } 
     }, 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 1 
      } 
     }, 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 0 
      } 
     }, 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 0 
      } 
     }, 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 0 
      } 
     }, 
     { 
      "landingPage": { 
       "landingPageMail": "[email protected] ", 
       "landingPageLeads": 0 
      } 
     } 
    ], 
    "totalLeads": 2 
} 

Это основная линия:

$subTot = array_sum(array_slice($data, $key*count($formIds), count($formIds))); 

Умножая ток mails_array ключа для $formIds мы можем получить, начиная $data ключа для текущего элемента, то мы можем извлечь из $data только значения, связанного с текущей электронной почтой и суммируем их с помощью array_sum(). Сумма добавляется к новому дочернему элементу landingPageData, а значение totalLeads увеличивается на него.


+0

Это просто чистый обалденный !!! Благодаря! Он работает на 100%, как я хотел! –