Y
Y
Yoshinon Eared2018-03-08 12:07:58
1C-Bitrix
Yoshinon Eared, 2018-03-08 12:07:58

How to get an array in a specific format?

Good day!
Straight to the point. There is the following line of code in the Bitrix module that forms an array:

Array formation
$arBasketItems = ['NAME' => $arItems['NAME'], 'DETAIL_PAGE_URL' => $arItems['DETAIL_PAGE_URL'], 'EXTERNAL_CODE' => $arItems['PRODUCT_XML_ID']];
print_r is obtained according to this pattern:
Output array
Array 
( 
    [0] => Array 
    ( 
        [NAME] => Название товара 1
        [EXTERNAL_CODE] => Уникальный внешний код 1
    )
    [1] => Array 
    ( 
        [NAME] => Название товара 2
        [EXTERNAL_CODE] => Уникальный внешний код 2
    )
    [2] => Array 
    ( 
        [NAME] => Название товара 1
        [EXTERNAL_CODE] => Уникальный внешний код 1  
    )
)
What is needed?
Get an array like this:
Desired result
Array 
( 
    [0] => Array 
    ( 
        [NAME] => Название товара 1
        [EXTERNAL_CODE] => Уникальный внешний код 1
        [COUNT] => Количество товара (2)
    )
    [1] => Array 
    ( 
        [NAME] => Название товара 2
        [EXTERNAL_CODE] => Уникальный внешний код 2
        [COUNT] => Количество товара (1)
    )
)

Those. you need to get an array only with a unique name or external code, as well as the amount in which it was before the conversion.
I tried to be smart with array_unique and array_search through a foreach loop - nothing really happened.
I would be grateful for any help!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
coderisimo, 2018-03-08
@Aquinary

sandbox.onlinephpfunctions.com/code/6c5f50911f2473...
run it and see the result

A
Arman, 2018-03-08
@Arik

?

$result = [];
foreach ($arBasketItems as $d) {
    if (!isset($result[$d['NAME']])) {
        $result[$d['NAME']] = $d;
        $result[$d['NAME']]['count'] = 0;
    }
    $result[$d['NAME']]['count']++;
}
$result = array_values($result);

T
twobomb, 2018-03-08
@twobomb

$arBasketItems = [];
foreach($arItems as $key => $val){
  foreach($arBasketItems as $key1 => $val1)
    if($val1['NAME'] == $val['NAME'] || $val1['EXTERNAL_CODE'] == $val['EXTERNAL_CODE'] ){
      $arBasketItems[$key1]['COUNT']++;
      goto end;
    }
  array_push($arBasketItems,['NAME' => $val['NAME'],'EXTERNAL_CODE' => $val['NAME'], 'COUNT' => 1]);
  end:
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question