array( "NO"=>array( -6ren">
gpt4 book ai didi

php - 显示此数组结果的最佳方式是什么

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:32 27 4
gpt4 key购买 nike

我有一个多维数组

array(
"Airportbus"=>array(
"NO"=>array(
"from"=>"Barcelona",
"to"=>"Gerona"
)
),
"flight"=>array(
"SK455"=>array(
"from"=>"Gerona",
"to"=>"Stockholm",
"seat"=>"3A"
),
"SK22"=>array(
"from"=>"Stockholm",
"to"=>"New york",
"gate"=>"Gate 22",
"description"=>"Baggage wiil be transfered from your last leg",
"seat"=>"7B"
)
),
"train"=>array(
"78A"=>array(
"from"=>"Madrid",
"to"=>"Barcelona",
"seat"=>"45B"
)
)
);

我想打印这样的结果。

1. Take train 78A from Madrid to Barcelona. Sit in seat 45B. 
2. Take the airport bus from Barcelona to Gerona Airport. No seat assignment.
3. From Gerona Airport, take flight SK455 to Stockholm. Gate 45B, seat 3A. Baggage drop at ticket counter 344.
4. From Stockholm, take flight SK22 to New York JFK. Gate 22, seat 7B. Baggage will we automatically transferred from your last leg.

这里的问题是

1.一些数组有更多的元素,它们具有不同的键 "gate","description"。2.结果中打印了一些额外的文本,“Sit in”,“Take”。

我尝试打印结果

$message = "";


if(issset($result['key']))
{
$message += " some text ".$result['key']. " some text ",
}
if(issset($result['key2']))
{
$message += " some text ".$result['key2']. " some text ",
}
if(issset($result['key2']))
{
$message += " some text ".$result['key2']. " some text ",
}

我认为 if 效率低下,因为每次添加新的数组键时我都必须添加更多代码。

遇到这种情况有没有更好的办法,求助。提前致谢:)

最佳答案

我希望这个 ruff 素描能带你到某个地方

$out='';
foreach($resut as $k=>$v){
if($k=='Airportbus'){
//process bus
}

if($k=='Train'){
//process train
foreach($v as $kk=>$vv){

$trainid=$kk;
$from=$v[$kk]['from'];
$to=$v[$kk]['to'];
$seat=$v[$kk]['seat'];
$out .='you sit in.'$seat.' from '.$from.' to '.$to.' on train: '.$trainid;
}
}

}

替代创建函数:

function train($data){
foreach($data as $kk=>$vv){

$trainid=$kk;
$from=$v[$kk]['from'];
$to=$v[$kk]['to'];
$seat=$v[$kk]['seat'];
$out .='you sit in.'$seat.' from '.$from.' to '.$to;
}

return $out;

}

关于php - 显示此数组结果的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26029876/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com