数组中对象的名称会导致顺序发生更改


Name of object in array causes a change in order

使用以下代码:

//turn items into an array
$item_array = array('abc','xyz2','Good','nice-b');
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product_items = array();
$productList = array();
$result = $mysqli->query("SELECT Name, WebsitePrice as price, WebsiteStock as stock from table_products where Name IN ('$item_implode')");
if ($result->num_rows > 0) {
    $x = 1;
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $product_items[$x]["Name"] = $row['Name'];
        $product_items[$x]["price"] = $row['price'];
        $product_items[$x]["stock"] = $row['stock'];
        $x = $x + 1;
    }
} else {
    echo "0 results";
}

我得到这个输出:

abc- 99 - yes
xyz - 20 - yes
Good - 30 - yes
nice-b - 55 - yes

但是当我使用一个名为Hello1而不是Good的项目时,比如:

$item_array = array('abc','xyz2','Hello1','nice-b');

我得到这个输出:

abc- 99 - yes
Hello1 - 77 - yes
xyz - 20 - yes
nice-b - 55 - yes

这意味着对象的名称导致数组的顺序发生了一些变化,并且它成为第二个项,即使它应该是第三个

是什么原因造成的?

在查询中使用ORDER BY FIELD(Name, 'abc','xyz2','Good','nice-b');。您可以使用$item_implode来实现可重用性。

[从评论中获取]

在SQL世界中,顺序不是一组数据的固有属性。因此,除非您使用ORDERBY子句查询数据,否则您的RDBMS无法保证您的数据将以特定的顺序返回,甚至以一致的顺序返回。

不能保证MySQL会按照您在IN子句中设置ID的顺序返回结果。

稍后编辑:根据您最后的评论,您可以执行以下操作:

if ($result->num_rows > 0) {
    $product_items = array_flip($item_array);
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $product_items[$row['Name']] = array();
        $product_items[$row['Name']]["Name"]  = $row['Name'];
        $product_items[$row['Name']]["price"] = $row['price'];
        $product_items[$row['Name']]["stock"] = $row['stock'];
    }
}