我正在尝试使用PHP创建一个二维数组,但仍然没有弄清楚。
$value = 3;
$sql = "SELECT country, capital FROM world WHERE client = 2 ";
$myArray = array();
try {
foreach ($connection->query($sql) as $row)
{
for($i=0; $i<$value; $i++){
$myArray[$i] = array($row['country'], $row['capital']);
}
}
}
我尝试了函数"array_push",但它不是获得特定值的最佳方式。
您正在对查询的单个结果进行循环。for()
循环是完全不必要的:
$myArray = array();
foreach ($connection->query($sql) as $row)
$myArray[] = array($row['country'], $row['capital']);
}
你不应该需要for循环:
$sql = "SELECT country, capital FROM world WHERE client = 2 ";
$myArray = array();
foreach ($connection->query($sql) as $row) {
$myArray[] = array("country" => $row['country'], "capital" => $row['capital']);
}
您不需要for
循环,并且由于您在查询中指定列,因此只需为关联数组执行此操作:
foreach ($connection->query($sql, PDO::FETCH_ASSOC) as $row)
$myArray[] = $row;
}
或者如果你想要数字索引,那么:
$connection->query($sql, PDO::FETCH_NUM)
或者您想访问$myArray['England']
之类的东西并获得London
?然后像这样构建数组:
foreach ($connection->query($sql, PDO::FETCH_ASSOC) as $row)
$myArray[$row['country']] = $row['capital'];
}