1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【PHP】PHPでコントロールブレイク

Last updated at Posted at 2021-10-16

#やりたいこと

同じ名前のレコードのデータがあったら、それぞれデータが異なるので復数欲しい

※名前が昇順である前提

<?php
$data = [
    ['name' => '田中',  '国語の点数' => 777],
    ['name' => '渡部',  '国語の点数' => 62],
    ['name' => '品川',  '国語の点数' => 23],
    ['name' => '品川',  '国語の点数' => 4343],
    ['name' => '滝谷',  '国語の点数' => 93],
    ['name' => '川原田','国語の点数' => 55],
    ['name' => '一色',  '国語の点数' => 27],
    ['name' => '一色',  '国語の点数' => 89],
    ['name' => '高橋',  '国語の点数' => 555],
    ['name' => '高橋',  '国語の点数' => 9999],
];



    foreach ($data as $cnt => $row) {
        if($cnt === 0){
            $key = $row['name'];
            $store[] = $row['国語の点数'];
        }
        if($key === $row['name']){
            $key = $row['name'];
            $store[] = $row['国語の点数'];
        }else{
            $result[$key] = implode(',', array_unique($store));
            $key = $row['name'];
            $store = [];
            $store[] = $row['国語の点数'];
        }
    }

    $result[$row['name']] = implode(',', array_unique($store));

var_dump($result);


#結果

array(7) {
  ["田中"]=>
  string(3) "777"
  ["渡部"]=>
  string(2) "62"
  ["品川"]=>
  string(7) "23,4343"
  ["滝谷"]=>
  string(2) "93"
  ["川原田"]=>
  string(2) "55"
  ["一色"]=>
  string(5) "27,89"
  ["高橋"]=>
  string(8) "555,9999"
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?