2014-09-25 4 views
2

у меня есть массив multidimentionlaКаков наилучший способ отображения результата этого массива

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.Каждый дополнительный текст печатается в результате: «Сядьте», «Возьмите».

я пытался напечатать результат с

$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 ", 
} 

Я думаю, если это неэффективно, потому что каждый раз, когда ключ нового массива добавил я должен добавить больше коды.

есть ли лучший способ сделать в такой ситуации, пожалуйста, помогите. Заранее спасибо :)

+0

Хорошо, по крайней мере, начать с петли. ваш массив не соответствует вашему результату. Как вы узнали, что заказ - поезд-автобус-рейс, у массива есть автобус-полет-поезд –

+0

@ Дагон, пожалуйста, предоставьте мне простой пример :( –

+0

@ Дагон, мм нет заказа :( –

ответ

1

Я надеюсь, что это ерш эскиз получает вас где-то

$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; 

} 
+0

хорошая идея ..... :). у вас есть еще какие-то предложения –

+0

, что еще вам нужно? –

+1

вам может понравиться создавать функции по одному для каждого транспорта, анализировать массив и возвращать строку, немного чистить оценку –

1

Это может делать то, что вам нужно, а также (по крайней мере, достаточно близко):

$transport_data = YOUR_DATA; 

$count = 1; 
foreach ($transport_data as $transport_type => $transports) { 
    foreach($transports as $transport_id => $transport_details) { 
     echo $count . "." . " Take " . $transport_type . " " . $transport_id . " "; 
     echo "from " . $transport_details['from'] . " to " . $transport_details['to'] . ". "; 

     echo "Seating is "; 
     if(array_key_exists('seat', $transport_details)) { // if seat exists, display it 
      echo "Seat " . $transport_details['seat'] . ". "; 
     } else { 
      echo "not assigned. "; 
     } 

     echo "Gate is "; 
     if(array_key_exists('gate', $transport_details)) { // if gate exists, display it 
      echo $transport_details['gate'] . ". "; 
     } else { 
      echo "not assigned. "; 
     } 

     if(array_key_exists('description', $transport_details)) { // if description exists, display it 
      echo $transport_details['description'] . ". "; 
     } 
     echo "\n"; 
     $count = $count + 1; 
    } 
} 

Выход:

1. Take Airportbus NO from Barcelona to Gerona. Seating is not assigned. Gate is not assigned. 
2. Take flight SK455 from Gerona to Stockholm. Seating is Seat 3A. Gate is not assigned. 
3. Take flight SK22 from Stockholm to New york. Seating is Seat 7B. Gate is Gate 22. Baggage wiil be transfered from your last leg. 
4. Take train 78A from Madrid to Barcelona. Seating is Seat 45B. Gate is not assigned. 
0

Мой процедурное решение без проверки или комментариев:

<?php 

function printDefaultTransportation($properties) { 
    $type = $properties['type']; 
    $from = $properties['from']; 
    $to = $properties['to']; 
    $id = isset($properties['id']) ? $properties['id'] : null; 
    $seat = isset($properties['seat']) ? $properties['seat'] : null; 

    echo "Take $type"; 
    if($id !== null) { 
     echo " $id"; 
    } 
    echo " from $from to $to."; 
    echo isset($seat) ? " Sit in $seat." : ' No seat assignment.'; 
} 

function printAirportTransportation($properties) { 
    $id = $properties['id']; 
    $from = $properties['from']; 
    $to = $properties['to']; 
    $seat = isset($properties['seat']) ? $properties['seat'] : null; 
    $gate = isset($properties['gate']) ? $properties['gate'] : null; 
    $description = isset($properties['description']) ? $properties['description'] : null; 

    echo "From $from Airport, take flight $id to $to."; 
    if($gate !== null) { 
     echo " $gate"; 
     if($seat !== null) { 
      echo ", seat $seat"; 
     } 
     echo '.'; 
    } else if($seat !== null) { 
     echo " Seat $seat."; 
    } 
    if($description !== null) { 
     echo " $description."; 
    } 
} 

function printTransportation($type, $id, $extra) { 
    static $functionsTypesMap = ['train'  => 'printDefaultTransportation', 
           'airportbus' => 'printDefaultTransportation', 
           'flight'  => 'printAirportTransportation']; 

    $properties = array_merge(['type' => $type, 'id' => $id], $extra); 
    call_user_func($functionsTypesMap[$type], $properties); 
} 

function printTransportations(array $transportations) { 
    foreach($transportations as $k => $v) { 
     $transportations[strtolower($k)] = $v; 
    } 

    $i = 1; 
    static $orderedTypes = ['train', 'airportbus', 'flight']; 
    foreach($orderedTypes as $type) { 
     if(!isset($transportations[$type])) { 
      continue; 
     } 

     foreach($transportations[$type] as $id => $properties) { 
      if($i > 1) { 
       echo "\n"; 
      } 
      echo "$i. "; 
      printTransportation($type, 
           (strtolower($id)==='no'? null : $id), 
           $properties); 
      ++$i; 
     } 
    } 
} 

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

printTransportations($arr); 

Выход:

 
1. Take train 78A from Madrid to Barcelona. Sit in 45B. 
2. Take airportbus from Barcelona to Gerona. No seat assignment. 
3. From Gerona Airport, take flight SK455 to Stockholm. Seat 3A. 
4. From Stockholm Airport, take flight SK22 to New york. Gate 22, seat 7B. Baggage wiil be transfered from your last leg.

Комментарии:

  • Ворота отсутствует в "полете SK455", потому что вход не имеет.
  • «Нью-Йорк» выводится как «Нью-Йорк» (это значение массива).
  • Я думаю, что вместо использования массива вы должны были использовать классы.
Смежные вопросы