第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

構(gòu)建數(shù)組路徑

構(gòu)建數(shù)組路徑

PHP
子衿沉夜 2023-07-15 17:21:00
我正在嘗試構(gòu)建數(shù)組路徑以減少代碼。原因是有大約 50 條長路徑,我想減少代碼庫。對于“test-2”,變量“$path”可以被硬編碼,同時右側(cè)“key-X”應(yīng)該能夠調(diào)整,例如用于以后的 for 循環(huán)。問題:是否可以構(gòu)建“test-2”中描述的數(shù)組路徑?想要的結(jié)果:測試 1:60測試 2:60<?php$arrayWithPrettyLongName = [  'level_1' => [    'key_1' => 10,    'key_2' => 20,    'key_3' => 30,  ]];// Test-1 // Works fine!$result_1 =$arrayWithPrettyLongName['level_1']['key_1'] +$arrayWithPrettyLongName['level_1']['key_2'] +$arrayWithPrettyLongName['level_1']['key_3'] ;echo $result_1;// Test-2 // Throws errors.$path = "$arrayWithPrettyLongName['level_1']";$result_2 =$path . ['key_1'] +$path . ['key_2'] +$path . ['key_3'] ;echo $result_2;錯誤PHP Parse error:  syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in Xxx.php on line 18
查看完整描述

2 回答

?
吃雞游戲

TA貢獻(xiàn)1829條經(jīng)驗 獲得超7個贊

我認(rèn)為您真正想知道的是如何創(chuàng)建數(shù)組引用。您可以通過在數(shù)組名稱前添加 & 符號來實現(xiàn)此目的


<?php


$arrayWithPrettyLongName = [

  'level_1' => [

    'key_1' => 10,

    'key_2' => 20,

    'key_3' => 30,

  ]

];


// Test-1 // Works fine!


$result_1 =

$arrayWithPrettyLongName['level_1']['key_1'] +

$arrayWithPrettyLongName['level_1']['key_2'] +

$arrayWithPrettyLongName['level_1']['key_3'] ;


echo $result_1;

echo "\n";



//Just create an array reference here, by preceding the name with an `&`

$path = &$arrayWithPrettyLongName['level_1'];



//Also remove the `.` symbol here. That's not the correct syntax

$result_2 =

$path['key_1'] +

$path['key_2'] +

$path['key_3'] ;


echo $result_2;

但看!如果你真的想減少代碼,難道就不能這樣做嗎?


$result_3 = 0;

foreach ($arrayWithPrettyLongName['level_1'] as $value){

    $result_3 += $value;

}

echo $result_3;

如果以后數(shù)組變大,保存就會很麻煩。


查看完整回答
反對 回復(fù) 2023-07-15
?
一只斗牛犬

TA貢獻(xiàn)1784條經(jīng)驗 獲得超2個贊

像這里一樣工作:


    <?php


$arrayWithPrettyLongName = [

  'level_1' => [

    'key_1' => 10,

    'key_2' => 20,

    'key_3' => 30,

  ]

];


// Test-1


$result_1 =

$arrayWithPrettyLongName['level_1']['key_1'] +

$arrayWithPrettyLongName['level_1']['key_2'] +

$arrayWithPrettyLongName['level_1']['key_3'] ;


echo $result_1; //output 60


// Test-2


$path = $arrayWithPrettyLongName['level_1'];


$result_2 =

$path['key_1'] +

$path['key_2'] +

$path['key_3'] ;


echo $result_2; //output 60


?>

你錯了$path = "$arrayWithPrettyLongName['level_1']";必須是沒有""

另一個改變是$path .必須是$path['key_1'];


查看完整回答
反對 回復(fù) 2023-07-15
  • 2 回答
  • 0 關(guān)注
  • 186 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號