我有以下数组,我想将其中的每个数组转换为单独的字符串。换句话说,将数组分成多个部分。

  $formatsArray = $_POST['formats'];
      $topicsArray = $_POST['topics'];


这是因为我想在以下查询中包括单个字符串“

  $resources = "select * from resources where
                    stage LIKE '%".$stage."%'
                    AND format LIKE '%".$formats."%'";


      $run_query = mysqli_query($con, $resources);


这是因为format需要一个单独的字符串来进行比较,例如假设数组为["video", "blogs", "articles"],如果要与video,blogs,articles进行比较,而与视频,博客或文章进行比较,则该格式将不起作用。

我希望这一点很清楚,如有任何澄清,请告知。

祝一切顺利,

更新:

$formats = explode(',', $formatsArray);
      $topics = explode(',', $topicsArray);


      $resources = "select * from resources where
                    stage LIKE '%".$stage."%'
                    AND format LIKE '%".$formats."%' AND topic LIKE '%".$topics."%' ";


更新:

$run_query = mysqli_query($con, $resources);


  while($row = mysqli_fetch_array($run_query)) {

    $data[] = array(
      'format' => $row['format'],
      'title' => $row['title'],
      'costs' => $row['cost'],
      'stage' => $row['stage'],
      'topic' => $row['topic'],
      'link' => $row['link']
    );
  }


更新资料

  include('db.php');


  $query = 'select * from resources where ';
  $query .= 'stage LIKE :stage and';
  $execute[':stage'] = '%' . $stage . '%';
  if(!empty($_POST['formats'])){
  foreach($_POST['formats'] as $key => $format) {
      $query .= 'format LIKE :format' . $key . ' and ';
      $execute[':format' . $key] = '%' . trim($format) . '%';
  }
  }
  if(!empty($_POST['topics'])){
  foreach($_POST['topics'] as $key => $topic) {
      $query .= 'topic LIKE :topic' . $key . ' and ';
      $execute[':topic' . $key] = '%' . trim($topic)  . '%';
  }
  }
  $query = rtrim($query, ' and ');
  if(!empty($execute)) {
      $stmt = $con->prepare($query);
      $stmt->execute($execute);
  } else {
      echo 'You must search for something';
  }


      while($row = mysqli_fetch_array($query)) {

        $data[] = array(
          'format' => $row['format'],
          'title' => $row['title'],
          'costs' => $row['cost'],
          'stage' => $row['stage'],
          'topic' => $row['topic'],
          'link' => $row['link']
        );
      }

最佳答案

忽略准备好的语句的必要性,您可以执行以下操作:

  $formats = implode('","', $formatsArray);
  $topics = implode('","', $topicsArray);

  $resources = "select * from resources where
                stage LIKE '%".$stage."%'
                AND format IN(".$formats.") AND topic IN(\"".$topics."\") ";


通过在每个数组"之前和之后在每个,之前添加implode,您的数组将变为

video","blogs","articles


因此,我们需要将"添加到每个IN列表的开头和结尾。这将使最终查询像:

select * from resources where
stage LIKE '%".$stage."%'
AND format IN("video","blogs","articles") AND ...

关于php - 将数组转换为单个字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32302633/

10-12 12:20
查看更多