2015-10-15 4 views
-1

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

По существу, это обзорный веб-сайт. Я использую Bootstrap для отображения данных на разных вкладках. Данные вызывают через запрос jQuery ajax, и страница PHP возвращает JSON. Руль используется для визуализации данных в шаблоне.

В конце концов, я хотел бы отправить данные в примерно таком формате:

{ 
    review: { 
     reviewstotal: INT, 
     count: INT, 
     summary: { 
      //iterated 
      tab: INT, 
      [{ 
       Question:, 
       Value:, 
       Color: , 
       Percent:, 
      }, 
      { 
       Question:, 
       Value:, 
       Color: , 
       Percent:, 
      }] 
     } 
    } 
} 

Где я борюсь находится в разделе «Сводка». «Вопросы» находятся в массиве, и у меня есть «Значения» как другой массив. Значение цвета будет получено из инструкции if, проверяющей значение «Значение» и задающего значение css в шаблоне. Процент - это значение «Значение», умноженное на 10. Вот что я до сих пор собирал для создания массива.

$array = array(); 
$color =""; 

for ($x = 0; $x <= 5; $x++) { 
    $summary= []; 

    if (${"q{$x}"} <= 40){ 
     $color = "danger"; 
    } else if (${"q{$x}"} >= 70){ 
     $color = "success"; 
    } else { 
     $color = "warning"; 
    } 

    $summary = array_push ($array, $aquest[$x], ${"q{$x}"}, $color, ${"q{$x}"}*10); 
} 

Что я получаю, как результат:

"summary": ["The facilities of the school adequately provide for a positive learning/working experience.",null,"danger",0, 
"School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.)","9.50","danger",95, 
"School is well funded to provide students and faculty with adaquate materials to support their course offering.","9.50","danger",95, 
"Parent community is actively involved in supporting the school's mission and their child's education endeavors.","9.00","danger",90, 
"Classroom student to teacher ratios are kept low.","8.75","danger",87.5,null,"7.63","danger",76.3] 

То, что я пытаюсь добиться, хотя в том, что каждый раздел «Вопрос» обернут в его собственном массиве. Нравится:

"summary": [["The facilities of the school adequately provide for a positive learning/working experience.",null,"danger",0], 
["School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.)","9.50","danger",95], 
["School is well funded to provide students and faculty with adequate materials to support their course offering.","9.50","danger",95], 
["Parent community is actively involved in supporting the school's mission and their child's education endeavors.","9.00","danger",90], 
["Classroom student to teacher ratios are kept low.","8.75","danger",87.5,null,"7.63","danger",76.3]] 

И затем я могу добавить согласованный ключ для каждого из них.

ответ

1

Вы должны попробовать следующее -

$array = array(); 
$color =""; 

//taking this out from the scope of loop 
$summary= []; 
for ($x = 0; $x <= 5; $x++) { 


if (${"q{$x}"} <= 40){ 
    $color = "danger"; 
} else if (${"q{$x}"} >= 70){ 
    $color = "success"; 
} else { 
    $color = "warning"; 
} 

//this is where the diference lies. $summary is a multi-dimension array. 
//which means, each element of that array is an array itself. 
//So this is how we represent such stuff in php. 
//Element at index $x, is also defined as an array with keys containing the 
//required values. 
$summary[$x] = array( 
     "text" => $aquest[$x], 
     "somekey1" => ${"q{$x}"}, 
     "somekey2" => $color, 
     "somekey3" => ${"q{$x}"}*10 
); 
} 

//here you can print the summary. 
print_r($summary) 
+0

Спасибо, спасибо, спасибо! Вот и все! – user1557966

0

Вы хотите добавить массивы в массив, но в настоящее время вы добавляете переменные в массив. Итак, вам нужно обернуть $aquest[$x], ${"q{$x}"}, $color, ${"q{$x}"}*10 в массив.

$array = array(); 
$color =""; 

for ($x = 0; $x <= 5; $x++) { 
    $summary= []; 

    if (${"q{$x}"} <= 40){ 
     $color = "danger"; 
    } else if (${"q{$x}"} >= 70){ 
     $color = "success"; 
    } else { 
     $color = "warning"; 
    } 

    $summary = array_push ($array, array($aquest[$x], ${"q{$x}"}, $color, ${"q{$x}"}*10)); 
} 
Смежные вопросы