简体   繁体   中英

PHP implode() replacing all array values with “array”

As part of MySQL SELECT statement I'm trying to dynamically query the database.

Current code:

$stmt = $pdo->prepare('SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`="assignment" AND `TABLE_NAME`=:table AND `COLUMN_NAME` != :column1 AND `COLUMN_NAME` != :column2;');
  $criteria = [
    'table' => $_GET['section'],
    'column1' => 'jobid',
    'column2' => 'catid'
  ];
  $stmt->execute($criteria);

  $arr = array();

  echo '<form method="POST">';
  foreach ($stmt as $row){
    echo '<label>'.ucwords($row['COLUMN_NAME']).':</label>
    <input type="text" name="'.$row['COLUMN_NAME'].'"/><p>';
    $arr[] = $row;
  }
  echo '<input type="submit" value="Submit" name="submit"/>
      </form>';

  if (isset($_POST['submit']))
    echo $query = implode(',', $arr);

I've got it working just fine using $_POST values but for some reason it outputs:

Array,Array,Array,Array,Array

even though the var_dump() of $arr is:

    0 => 
    array (size=2)
      'COLUMN_NAME' => string 'title' (length=5)
      0 => string 'title' (length=5)
  1 => 
    array (size=2)
      'COLUMN_NAME' => string 'salary' (length=6)
      0 => string 'salary' (length=6)
  2 => 
    array (size=2)
      'COLUMN_NAME' => string 'location' (length=8)
      0 => string 'location' (length=8)
  3 => 
    array (size=2)
      'COLUMN_NAME' => string 'description' (length=11)
      0 => string 'description' (length=11)
  4 => 
    array (size=2)
      'COLUMN_NAME' => string 'category' (length=8)
      0 => string 'category' (length=8)

The implode function doesn't work the way that you want with an array of arrays. It takes the arrays in $arr and makes them into the string 'Array'. You can loop through the array and implode that way, for example,

$list = '';
foreach ($arr as $inner) {
    $list .= $inner['COLUMN_NAME'].',';
}
$list = rtrim($list,',');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM