#b-navbar { height:0px; display:none; visibility:hidden; }

ページ

2011年6月16日木曜日

PHP:配列の値を入れ替える関数


//テスト配列 
 $aaa = array();
 $aaa[0]["color"] = "red";
 $aaa[0]["image"] = "apple";
 $aaa[1]["color"] = "blue";
 $aaa[1]["image"] = "nasubi";
 $aaa[2]["color"] = "green";
 $aaa[2]["image"] = "hourensou";
 $aaa[3]["color"] = "yellow";
 $aaa[3]["image"] = "lemon";

//関数
//引数(対象配列,入替元,入替先)
 function SwapArray( $input, $nn, $mm ) {
    $val1 = $input[ $nn ] ;
    $val2 = $input[ $mm ] ;
    $input[ $nn ]= $val2;
    $input[ $mm ]= $val1;
    return $input;
 }

//test
 print_r( $aaa ) ;
 print "
"; $aaa = SwapArray ( $aaa , 1 ,2 ); print_r( $aaa ) ; print "
";
出力
Array
(
    [0] => Array
        (
            [color] => red
            [image] => apple
        )

    [1] => Array
        (
            [color] => blue
            [image] => nasubi
        )

    [2] => Array
        (
            [color] => green
            [image] => hourensou
        )

    [3] => Array
        (
            [color] => yellow
            [image] => lemon
        )

)

Array ( [0] => Array ( [color] => red [image] => apple ) [1] => Array ( [color] => green [image] => hourensou ) [2] => Array ( [color] => blue [image] => nasubi ) [3] => Array ( [color] => yellow [image] => lemon ) )
配列の[1]と[2]が入れ替わった

0 件のコメント:

コメントを投稿