简体   繁体   English

试图遍历 PHP 中的数组。 有一个更好的方法吗?

[英]Trying to loop through an array in PHP. Is there a better way to do this?

So I have three tables I am trying to fetch data from.所以我有三个表我试图从中获取数据。

A Customers table An Orders table and a Parts table客户表 订单表和零件表

I am trying to basically produce a report that displays what the user bought and how much it cost.我试图基本上生成一个报告,显示用户购买了什么以及它的成本。 This involves getting their accountID from Customers, joining that with the accountID attached to the OrderID in Orders then taking the PartID within orders, attached to orderID, and returning the partName.这涉及从客户那里获取他们的 accountID,将其与附加到 Orders 中的 OrderID 的 accountID 连接起来,然后获取订单中的 PartID,附加到 orderID,并返回 partName。

What I was thinking was looping through a php array and using sql to populate it with customerNames then use sql for the other queries to sort everything by name.我在想的是循环遍历一个 php 数组并使用 sql 用 customerNames 填充它,然后使用 sql 进行其他查询以按名称对所有内容进行排序。 Not sure if that is the best way to do that though since INNER JOIN wasn't working for me when trying to query 3 tables.不确定这是否是最好的方法,因为在尝试查询 3 个表时 INNER JOIN 对我不起作用。 Here is my code for the array:这是我的数组代码:

$sql = "SELECT firstName FROM Customers INNER JOIN Orders ON 
    Customers.accountID=Orders.accountID";
$statement = $conn->query($sql);

$i = 0;
$NameArray = array();

while ($Names = $statement->fetch()) {
    echo "<br>";
    echo $Names[0];
    $NameArray[$i];
    echo "<br>";
    $i++;
}

this give the error undefined index.这给出了错误未定义的索引。 Not really sure why不太清楚为什么

$sql = "SELECT firstName FROM Customers INNER JOIN Orders ON 
Customers.accountID=Orders.accountID";
$statement = $conn->query($sql);

$i = 0;
$NameArray = array(); ***CREATES an empty array

while ($Names = $statement->fetch()) {
    echo "<br>";
    echo $Names[0];
    $NameArray[$i];  ***Should start with 'echo'.
                        Also, there's nothing assigned to $NameArray[$i]
    echo "<br>";
    $i++;
}

In the above code, I found 2 issues and noted them, but neither will solve your index error.在上面的代码中,我发现了 2 个问题并记录了它们,但都不能解决您的索引错误。 You still have to assign a value to $NameArray[$i] before you can echo it without the index error.您仍然必须为 $NameArray[$i] 分配一个值,然后才能在没有索引错误的情况下回显它。

Regarding your loop to lookup the info, you might be able to just add the [Cost] field to your SQL like this:关于查找信息的循环,您可以像这样将 [Cost] 字段添加到 SQL 中:

SELECT Customers.firstName, Orders.Cost, Orders.PartID FROM Customers INNER JOIN Orders ON 
Customers.accountID=Orders.accountID

You can subsequently add the Parts table to the query with the following join:随后您可以使用以下连接将 Parts 表添加到查询中:

Orders.PartID = Parts.PartID

And then simply add Parts.partName to the SELECT fields.然后只需将 Parts.partName 添加到 SELECT 字段。

I guess you are running mysqli我猜你正在运行 mysqli

you will need to list all the table column for both customer and order table.您需要列出客户和订单表的所有表列。

Now for testing, am adding a column name for customer and quantity for order tables.现在为了测试,我为客户和订单表添加了一个列名。

lets assume that we want to select Customers.name and Orders.quantity from database让我们假设我们要从数据库中选择 Customers.name 和 Orders.quantity

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = 'SELECT Customers.accountID, Customers.name, Orders.quantity, Orders.accountID FROM Customers
LEFT JOIN Orders ON Customers.accountID=Orders.accountID
ORDER BY Customers.accountID';

    $result = mysqli_query($con,$query);
    while($row = mysqli_fetch_assoc($result)){ 
  $order_quantity = $row['quantity'];
  $customer_name = $row['name'];

//you can now echo

echo $customer_name.' '.$order_quantity.'<br/>';
}
?>

Now since you wants to generate an arrays, your code will look like below现在,由于您要生成数组,因此您的代码将如下所示

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

 $res_arr = array();

$query = 'SELECT Customers.accountID, Customers.name, Orders.quantity, Orders.accountID FROM Customers
LEFT JOIN Orders ON Customers.accountID=Orders.accountID
ORDER BY Customers.accountID';

    $result = mysqli_query($con,$query);
    while($row = mysqli_fetch_assoc($result)){ 
  $order_quantity = $row['quantity'];
  $customer_name = $row['name'];

$res_arr[] = array("customer name" =>$customer_name, "order quqntity" =>$order_quantity);
}
 echo json_encode($res_arr);
    exit
?>

or you can just do as per below if you do not want the resultant array response to be parameter initialized..或者,如果您不希望对结果数组响应进行参数初始化,则可以按照以下操作。

$result = mysqli_query($con,$query);
    while($row = mysqli_fetch_array($result)){    

        $res_arr[] = $row;
}
    echo json_encode($res_arr);
    exit;

Actually $NameArray is an empty array.实际上 $NameArray 是一个空数组。

Probable you want something like: $NameArray[$i] = $Names[0];可能你想要这样的东西: $NameArray[$i] = $Names[0]; and at the end of the loop you will have all the firstName(s) in $NameArray在循环结束时,您将拥有 $NameArray 中的所有 firstName(s)

Sorting by name can make mysql better按名称排序可以让mysql更好

$sql = "select firstName
from Customers AS Customers
inner join Orders AS Orders on Customers.accountID = Orders.accountID
GROUP BY Customer.accountID
ORDER BY Customer.firstName";

... ...

$i=0;
while($Names=$statement->fetch()){
    echo $Names[$i];
   $i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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