連想配列の操作

1 minuteReading Time

array()関数を使った多次元連想配列の作成

まずは連想配列

$array = array(
    'coffee' => array(
            'code'  => '123',
            'price' => '500円'
        )

);
print_r ($array);

//

実行結果 Array ( [coffee] => Array ( => 123 [price] => 500円 ) )

多次元配列

$array2 = [
    ['coffee',123,'500'],
    ['tea',120,'480']
];
print_r ($array2);

実行結果:
Array (
[0] => Array ( [0] => coffee [1] => 123 [2] => 500 )
[1] => Array ( [0] => tea [1] => 120 [2] => 480 )
)

多次元連想配列

$array = array(
    'coffee' => array(
            'code'  => '123',
            'price' => '500円'
    ),
    'tea'   => array(
            'code'  => '120',
            'price' => '480円'
    )
);

実行結果:
Array (
[coffee] => Array (
=> 123 [price] => 500円 )
[tea] => Array (
=> 120 [price] => 480円 )
)

多次元連想配列を1行ずつ入れていく場合結果は上記と同じ

$array3['coffee']['code'] = '123';
$array3['coffee']['price'] = '500円';
$array3['tea']['code'] = '120';
$array3['tea']['price'] = '480円';

多次元連想配列の追加

$array[] = array(
    'coffee' => array(
            'code'  => '123',
            'price' => '500円'
    )
);
$array1 = array(
    'tea' => array(
            'code'  => '120',
            'price' => '480円'
    )
);
$array[] = $array1;

実行結果:
Array (
[0] => Array ( [coffee] => Array ( [pcode] => 123 [price] => 500円 ) )
[1] => Array ( [tea] => Array ( [pcode] => 120 [price] => 480円 ) )
)

構造をもう少しシンプルに

$array[] = array(
    'name'  => 'coffee',
    'dcode'  => '123',
    'price' => '500円',
);
$array1 = array(
    'name'  => 'tea',
    'dcode'  => '120',
    'price' => '480円',
);
$array[] = $array1;
print_r ($array);

Array (
[0] => Array ( [name] => coffee [dcode] => 123 [price] => 500円 )
[1] => Array ( [name] => tea [dcode] => 120 [price] => 480円 )
)

前の配列を2つにすると

$array = array(
        array(
            'name'  => 'coffee',
            'pcode'  => '123',
            'price' => '500円',
        ),
        array(
            'name'  => 'water',
            'pcode'  => '212',
            'price' => '120円',
    ));

$array1 = array(
            'name'  => 'tea',
            'code'  => '120',
            'price' => '480円',
    
);
array[] = $array1;
print_r ($array);

実行結果:
Array (
[0] => Array ( [name] => coffee [pcode] => 123 [price] => 500円 )
[1] => Array ( [name] => water [pcode] => 212 [price] => 120円 )
[2] => Array ( [name] => tea => 120 [price] => 480円 )
)

1行ずつでも同じ

$array2[0]['coffee']['pcode'] = '123';
$array2[0]['coffee']['rice'] = '500円';
$array2[1]['tea']['pcode'] = '120';
$array2[1]['tea']['price'] = '480円';

$array3['beer']['pcode'] = '200';
$array3['beer']['price'] = '500円';

$array2[] = $array3;
print_r ($array2);

実行結果:
Array (
[0] => Array ( [coffee] => Array ( [pcode] => 123 [rice] => 500円 ) )
[1] => Array ( [tea] => Array ( [pcode] => 120 [price] => 480円 ) )
[2] => Array ( [beer] => Array ( [pcode] => 200 [price] => 500円 ) )
)

0
0
28
1 minuteReading Time

こんにちは。 グローバルリンクです。

KbxBotIcon