PHP数组和API的问题

时间:2014-01-16 23:43:10

标签: php arrays

我正在研究一个关于SEMRUSH api的项目,结果正在$ field1; field2如此分离;

我得到的当前结果基于其列有5个reslts彼此相邻,但是我只需要第二个数组

     if (isset($_POST['search_term'])) {

       $kwtext1 = str_replace(" ", '+', ($_POST['search_term']));
       $kwtext = str_replace("\r", '', trim($kwtext1));
       $kwdata = array();
        $kwlines = explode("\n", $kwtext);

       $db = "us";
       $limit = "10";
       }


    foreach ($kwlines as $kw) {

    usleep(100);

    $u = 'http://' . $db . '.api.semrush.com/?action=report&type=phrase_this&phrase=' . $kw . '&key=' . $key . '&display_limit=' . $limit . '&display_offset=0&export=api&export_columns=Ph,Nq,Cp,Co,Nr';

      $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $u);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

      $answer        = curl_exec      ( $ch );

    $kwdata = explode ( "\n", trim ( $answer ) );
     $kwfields = explode ( ";", array_shift ( $kwdata ) );

      if ( count ( $kwdata ) > 0 )
      {
    ?>
    <table class="output">
    <tr><th>Domain 1</th>
   <?php $csv_output .= ' ' . ", " . 'Domain' . ", ";?>

    <?
        foreach ( $kwfields as $field )
        {
  ?>
      <th><?= $field; ?></th>
    <?php $csv_output .= $field . ", ";?>
    <?
        }
    ?>
    </tr>
    <?
        foreach ( $kwdata as $dataline )
        {
          $values = explode ( ";", $dataline, count ( $kwfields ) );
     ?>
    <tr><td><? echo $kw ?></td>
    <?php $csv_output .= $kw . ", ";?>
   <?
             foreach ( $values as $value )
          {
    ?>
      <td><?= $value; ?></td>
   <?php $csv_output .= $value . ", ";?>
    <?
            }
  ?>
    </tr>
          <?
        }
         ?>
        </table>
     <?
      }
         else
        {
       ?>
           No data found for your request
       <?
              }
     }


      ?>

1 个答案:

答案 0 :(得分:1)

如果你只是想要第二个结果,并且你知道你将得到5个结果,那么我想改变一行:

$kwfields = explode(";", array_shift($kwdata));

为:

$kwfields = explode(";", $kwdata[1]);

会奏效。

但如果你没有至少2行数据,这将失败。你保证得到2个或更多吗?如果没有,那么你需要检查一下。