PHP populates an associative array

I am creating a data.php file that returns a json file to an html file where I fill the grid with data from the data.php file. I need it to be an associative array in the following form:

[
 {"CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative"},
 {"CompanyName":"Ana Trujillo Emparedados y helados","ContactName":"Ana Trujillo","ContactTitle":"Owner"},
 {"CompanyName":"Antonio Moreno Taquera","ContactName":"Antonio Moreno","ContactTitle":"Owner"}
]

      

Now the problem is that I want this data.php to be kind of generic, which means I don't know the column name or the number of columns. The only way to do this is to use a switch statement, but that is not ideal (because I can make multiple cases, but what if the table has one more column) and not very elegant.

I bet it could be done much better, any ideas?

I tried using array_push (), but that doesn't work with associative arrays.

// get columnnames
for ($i = 0; $i < $result->columnCount(); $i++) {
    $col = $result->getColumnMeta($i);
    $columns[] = $col['name'];
}

// fill up array
while ($row = $result->fetch(PDO::FETCH_ASSOC))  {
    switch (count($columns);) {
        case 1 :
            $records[] = array($columns[0] => $row[$columns[0]]);
            break;
        case 2 :
            $records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]]);
            break;
        case 3 :
            $records[] = array($columns[0] => $row[$columns[0]], $columns[1] => $row[$columns[1]], $columns[2] => $row[$columns[2]]);
            break;
        case ... // and so on
}   
}

// send data to client
echo json_encode($records);

      

+3


source to share


2 answers


change the toggle code segment with this



$arr_tmp = array();
for($i = 0; $i < count($columns); $i++)
{
	$arr_tmp[$columns[$i]] = $row[$columns[$i]]
}
$records []= $arr_tmp;
      

Run codeHide result


0


source


You can iterate over the columns:



while ($row = $result->fetch(PDO::FETCH_ASSOC))  {
    $values = array();
    foreach ($columns as $column) {
        values[$column] = $row[$column];
    } 
    records[] = $values;
}

      

0


source







All Articles