Php 如何查看数组以提取数据

Php 如何查看数组以提取数据,php,arrays,database,foreach,while-loop,Php,Arrays,Database,Foreach,While Loop,您好,我正在尝试查询数据库并将结果($searchResults[])存储为数组: <?php if(isset($_POST['indexSearchSubmit'])) { foreach($_POST['industryList'] as $selected) { $_POST['industryList'] = $selected; $locationListResults = $_POST['locationList'];

您好,我正在尝试查询数据库并将结果($searchResults[])存储为数组:

<?php

if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
    {
        $_POST['industryList'] = $selected;
        $locationListResults = $_POST['locationList'];

        $results = mysqli_query($con,"SELECT * FROM currentListings 
WHERE location = '$locationListResults' AND industry = '$selected'");

        $searchResults = array();

        while($row = mysqli_fetch_array($results))
            {
                $searchResults[] = $row['industry'];
                $searchResults[] = $row['location'];
                $searchResults[] = $row['title'];
                $searchResults[] = $row['description'];
            }

    }
                mysqli_close($con);
}

?>
你喜欢这样做吗

<?php 
print_r($searchResults); // Prints all array elements
?>

您的代码将数据放入1D数组中。你可能想要别的东西,所以不要这个:

$searchResults[] = $row['industry'];
$searchResults[] = $row['location'];
$searchResults[] = $row['title'];
$searchResults[] = $row['description'];
这样做:

$tmp = array();

$tmp['industry'] = $row['industry'];
$tmp['location'] = $row['location'];
$tmp['title'] = $row['title'];
$tmp['description'] = $row['description'];

$searchResults[] = $tmp;
或者就是这个(感谢巴尔马):

这样可以将数据存储为二维数组。因此,您获得的每一行都保留在一个子数组中

要打印行(现在是二维数组),请在子数组上迭代:

foreach($one_of_searchResult_rows as $k => $v)
{
    // do whatever you need with $k and $v
}
让我们简单一点:

$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);

参考资料:

我想您需要一个2d阵列。请尝试以下代码段:

$searchResults = array();

    while($row = mysqli_fetch_array($results))
        {
            array_push($searchResults,$row);
        }
这将在最终SearchResults数组的每个单元格中将每一行作为关联数组推送。然后,您可以访问以下值:

echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result

我很感激你的回复,因为你可以告诉我我有点新,th k=>v代表什么?它代表数组中的键和值。当使用foreach方法时,它会显示我试图显示的所有4个字段,但仅显示一次,如果有意义的话,不会显示每个结果的所有4个字段。你能重新表述你的问题吗?使用foreach,我需要它显示数据库中与原始查询和每个结果有4个字段,分别是:行业、位置、地点、描述,但我只获取1个结果,只需
$searchResults[]=$row
这仍然不能解决echo$searchResult[0]
的问题,这是他的问题。
$serach_result=mysqli_fetch_all ($result,MYSQLI_NUM);
//you should use print_r while trying to print an array
print_r($search_result[0]);
$searchResults = array();

    while($row = mysqli_fetch_array($results))
        {
            array_push($searchResults,$row);
        }
echo $searchResults[0]['industry']; //and so on
echo $searchResults[0]; //Should print out the first match/row of the sql result