LoginSignup
0
0

【PHP】PHPの高度な配列操作 正規化されていない配列を結合

Last updated at Posted at 2022-09-09

コード

<?php
$query_data = [
    ['id'=> 1,'name'=>'イワーク','place'=>'渓谷,洞窟','level' => 10,'technique'=>'岩雪崩'],
    ['id'=> 1,'name'=>'イワーク','place'=>'砂漠,山頂','level' => 20,'technique'=>'岩石砲'],
    ['id'=> 2,'name'=>'ハガネール','place'=>'鉱山,地中','level' => 10,'technique'=>'メテオドライブ'],
    ['id'=> 2,'name'=>'ハガネール','place'=>'丘陵,窪地','level' => 20,'technique'=>'アイアンローラー'],
];
$res = [];
foreach($query_data as $value){
    if(empty($res[$value['id']])){
        $res[$value['id']] = [
            'id' => $value['id']
           ,'name' => $value['name']
        ];
    }
    foreach(explode(',',$value['place']) as $place){
        $res[$value['id']]['place_list'][] = $place;
    }
    
    $res[$value['id']]['lv_list'][(int)$value['level']] = [
        'level' => $value['level']
       ,'technique' => $value['technique']
    ];
}
var_dump($res);

結果

array(2) {
  [1]=>
  array(4) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(12) "イワーク"
    ["place_list"]=>
    array(4) {
      [0]=>
      string(6) "渓谷"
      [1]=>
      string(6) "洞窟"
      [2]=>
      string(6) "砂漠"
      [3]=>
      string(6) "山頂"
    }
    ["lv_list"]=>
    array(2) {
      [10]=>
      array(2) {
        ["level"]=>
        int(10)
        ["technique"]=>
        string(9) "岩雪崩"
      }
      [20]=>
      array(2) {
        ["level"]=>
        int(20)
        ["technique"]=>
        string(9) "岩石砲"
      }
    }
  }
  [2]=>
  array(4) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(15) "ハガネール"
    ["place_list"]=>
    array(4) {
      [0]=>
      string(6) "鉱山"
      [1]=>
      string(6) "地中"
      [2]=>
      string(6) "丘陵"
      [3]=>
      string(6) "窪地"
    }
    ["lv_list"]=>
    array(2) {
      [10]=>
      array(2) {
        ["level"]=>
        int(10)
        ["technique"]=>
        string(21) "メテオドライブ"
      }
      [20]=>
      array(2) {
        ["level"]=>
        int(20)
        ["technique"]=>
        string(24) "アイアンローラー"
      }
    }
  }
}
0
0
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
0
0