채택완료

배열합계 구하는것좀 조언좀 부탁드립니다.

배열명 : $candy
현재 candy배열 안에 값은 이렇게 들어가있습니다.

(
    [0] => Array
        (
            [알사탕] => 13
        )

    [1] => Array
        (
            [껌] => 1
        )

    [2] => Array
        (
            [껌] => 2
        )

    [3] => Array
        (
            [알사탕] => 2
        )

    [4] => Array
        (
            [호박사탕] => 2
        )
)

아래 이런식으로
(
    [0] => Array
        (
            [알사탕] => 15
        )

    [1] => Array
        (
            [껌] => 3
        )

    [2] => Array
        (
            [호박사탕] => 2
        )
)
각 사탕들의 합을 구하고싶습니다.

선배님들의 조언좀 부탁드립니다.

답변 2개

채택된 답변
+20 포인트

https://codeday.me/ko/qa/20190312/30330.html

좋은 방법이 해당 링크에있습니다

2019-11-07 (목) 22:19:12

스쿨 답변 그대로 복사&붙여넣기.

- https://phpschool.com/gnuboard4/bbs/board.php?bo_table=qna_function&wr_id=469020

* '초기화'하지 않으면, [Notice] Undefined index 오류 발생합니다.

Copy
<?php

$candy = [ // PHP v5.4 미만은 [] → array()
    ['알사탕'=>13],
    ['껌'=>1],
    ['껌'=>2],
    ['알사탕'=>2],
    ['호박사탕'=>2],
];

$temp = []; // 임시 배열
foreach ( $candy as $no=>$row ) {
    $key = key($row); // 알사탕, 껌, 껌, 알사탕, 호박사탕
    if ( !isset($temp[$key]) ) $temp[$key] = 0; // 초기화
    $temp[$key]+= $row[$key]; // 수량 더하기
}

↓

Copy
Array
(
    [알사탕] => 15
    [껌] => 3
    [호박사탕] => 2
)


질문에서 원하는 결과처럼 하려면 아래 코드 추가해주면 됩니다.

Copy
$candy = [];
foreach ( $temp as $k=>$v ) $candy[] = [$k=>$v];

↓
Copy
Array
(
    [0] => Array
        (
            [알사탕] => 15
        )

    [1] => Array
        (
            [껌] => 3
        )

    [2] => Array
        (
            [호박사탕] => 2
        )

)


‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥

* 정렬 추가, 참고 링크 추가.
 

Copy
<?php

$candy = [ // PHP v5.4 미만은 [] → array()
    ['알사탕'=>13],
    ['껌'=>1],
    ['껌'=>2],
    ['알사탕'=>2],
    ['호박사탕'=>2],
];

$temp = []; // 임시 배열
foreach ( $candy as $no=>$row ) {
    $key = key($row); // 알사탕, 껌, 껌, 알사탕, 호박사탕
    if ( !isset($temp[$key]) ) $temp[$key] = 0; // 초기화
    $temp[$key]+= $row[$key]; // 수량 더하기
}

arsort($temp); // 캔디수 큰 순으로. 작은 순은 asort();

$candy = [];
foreach ( $temp as $k=>$v ) $candy[] = [$k=>$v];


‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥‥

+ foreach()
- https://www.php.net/manual/en/control-structures.foreach.php

+ key()
- https://www.php.net/manual/en/function.key.php
- http://docs.php.net/manual/kr/function.key.php

+ arsort()
- https://www.php.net/manual/en/function.arsort.php
- http://docs.php.net/manual/kr/function.arsort.php

+ asort()
- https://www.php.net/manual/en/function.asort.php
- http://docs.php.net/manual/kr/function.asort.php

답변을 작성하려면 로그인이 필요합니다.