按schoolType过滤数组

时间:2017-07-19 20:02:36

标签: php html api

我正在调用一个返回给我一系列学校的API。我想按学校类型过滤该数组,并在下拉列表中显示学校类型。当我这样做时,我得到空值。

function getSchools() {
  $path = $GLOBALS['f1Settings']['baseUrl'] . '/v1/People/Schools.json';
  $r = $_SESSION['f1Obj']->fetchGetJson($path);
  $schoolarray = array();
  //loop through results to build array of schools
  if ($r) {
    foreach($r['schools']['school'] as $school) {
      array_push($schoolarray,array('name'=>$school['name'],'id'=>$school['@id']));
    }
  }
  array_multisort($schoolarray,SORT_ASC);
  echo(json_encode($schoolarray));
  }

输出数组的HTML:

<label for="school">School:</label>
<select id="school" class="required" name="school">
  <option value="">Select...</option>
</select>

1 个答案:

答案 0 :(得分:0)

如果r [&#39;学校&#39;] [&#39; school&#39;]已经是一个数组,那么您需要做的就是将它分配给循环外的数组。这将按名称对它们进行排序:

 if ($r) {
foreach($r['schools']['school'] as $school) {
  $schoolarray[ $school['name'] ] = $school;
 }
}

您的输出问题是您需要使用一些独特的东西,例如学校ID,作为给定的值,您可以循环显示学校名称。不知道你的HTML在哪里以及你如何提供它,但是一旦你有了你的schoolarray数组,那么你可以这样做:

<select id="school" class="required" name="school">
<?php
foreach ( $schoolarray as $name => $data )
{
   echo "<option value=\"data['@id']\">$name</option>";
}
?>
</select>

您可能需要将其编辑为正确的数组索引