LoginSignup
4
3

More than 5 years have passed since last update.

Ginqで2つの連想配列をJoinする例

Last updated at Posted at 2015-01-03
{
    "require": {
        "ginq/ginq": "dev-master"
    }
}
<?php
require_once 'vendor/autoload.php';

// 商品カテゴリ
$categories = array(
    array('id' => 1, 'name' => '果物'),
    array('id' => 2, 'name' => '魚'),
);
// 商品データ
$items = array(
    array('id' => 1, 'name' => 'りんご', 'price' => 100, 'category' => 1),
    array('id' => 2, 'name' => 'みかん', 'price' =>  80, 'category' => 1),
    array('id' => 3, 'name' => 'さんま', 'price' => 180, 'category' => 2),
    array('id' => 4, 'name' => 'マグロ', 'price' => 300, 'category' => 2),
);

$results = Ginq::from($items)  // 元になる配列
    ->join(
        $categories,            // 結合する配列
        '[category]',           // 元になる配列側の結合フィールド
        '[id]',                 // 結合する配列側の結合フィールド
        function($item, $category, $itemKey, $categoryKey) {
            // 元になる配列にあった行が $item、結合する配列にあった行が $category として渡される
            // 結合後の1行ごとにここが呼ばれるので、結合結果として採用する行(1行分)を返す(SELECTにあたる)
            return array('id' => $item['id'], 'name' => $item['name'], 'price' => $item['price'], 'category_name' => $category['name']);
        }
    );
?>
<table>
<?php foreach ($results as $result): ?>
<tr>
    <td><?php echo $result['id'] ?></td>
    <td><?php echo $result['name'] ?></td>
    <td><?php echo $result['price'] ?></td>
    <td><?php echo $result['category_name'] ?></td>
</tr>
<?php endforeach; ?>
</table>
4
3
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
4
3