LoginSignup
13
14

More than 3 years have passed since last update.

PHPでネストした連想配列を <input type="hidden"> の配列に組み立てる

Last updated at Posted at 2019-09-20

概要

元ネタ↓
php: generate html hidden input elements from a php array

Input

$data = [
    'transaction_id' => '123',
    'items' => [
        ['id' => '1', 'name' => 'cat'],
        ['id' => '2', 'name' => 'dog'],
    ],
];

Output

<input type="hidden" name="transaction_id" value="123">
<input type="hidden" name="items[0][id]" value="1">
<input type="hidden" name="items[0][name]" value="cat">
<input type="hidden" name="items[1][id]" value="2">
<input type="hidden" name="items[1][name]" value="dog">

実装

まじめに実装するとだるいので http_build_query 関数にキーの組み立て処理はすべて任せちゃいます。配列で出力されるので foreach で回してテンプレート内でよしなにどうぞ。

Pure PHP 向け

<?php

function buildHiddenInputs(array $data): array
{
    $pairs = explode('&', http_build_query($data, '', '&'));

    $inputs = [];
    foreach ($pairs as $pair) {
        [$key, $value] = explode('=', $pair);

        $inputs[] = sprintf(
            '<input type="hidden" name="%s" value="%s">',
            htmlspecialchars(urldecode($key), ENT_QUOTES, 'UTF-8'),
            htmlspecialchars(urldecode($value), ENT_QUOTES, 'UTF-8')
        );
    }

    return $inputs;
}

Laravel 向け

<?php

use Illuminate\Support\HtmlString;

function buildHiddenInputs(array $data): array
{
    $pairs = explode('&', http_build_query($data, '', '&'));

    $inputs = [];
    foreach ($pairs as $pair) {
        [$key, $value] = explode('=', $pair);

        $inputs[] = new HtmlString(sprintf(
            '<input type="hidden" name="%s" value="%s">',
            e(urldecode($key)),
            e(urldecode($value))
        ));
    }

    return $inputs;
}
13
14
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
13
14