我的PHP数组知识有限。我已经阅读了PHP数组-手册,但是里面的解释并不足以让我真正理解。
在我的if{} else{}
语句中,我有以下代码作为else{}
部分:
// Set up an array for the items
while($row = mysqli_fetch_array($result))
{
$source = $row['source'];
}
$items = array(
"id" => $id,
"source" => $source,
);
$_SESSION['items'] = $items;
假设我有以下项目:
Item A with an ID of 1 and source of foo
Item B with an ID of 2 and source of boo
Item C with an ID of 3 and source of goo
如果使用
item A
调用此函数,则创建的数组具有1
的ID和foo
的来源,只有这些内容放入了数组中。并且该数组会以以下方式输出:array(2) { ["id"]=> string(2) "25" ["source"]=> string(64) "https://www.alphahq.org/shop/views/assets/images/items/item2.jpg" }
现在如果函数立即被调用并传入item B
,数组将会被改变以包含item B
的变量,这是正确的吗?
我该如何将item A
和item B
添加到同一个数组中并将它们定义为单独的项?
所以基本上我应该如何做到以下几点?
array {
item A {
id => 1
source => foo
}
item B {
id => 2
source => boo
}
}
当添加一个项目时,只需构建数组。我将数组保存在会话中,这样在每次调用函数时检索和添加数组可能会很有帮助。
为了提供额外的帮助,附上完整的shopping-functions.php
文件以供参考。
<?php
session_start();
require('../../config/database-connect.php');
// Start a new order for a customer
$action = $_GET['action'];
$id = $_GET['id'];
// First make sure the action is not blank
if ($action == '') {
echo 'Please select an action';
}
if ($action == 'add') {
// Check if the id matches one in the database
$result = mysqli_query($con,"SELECT id, source FROM items WHERE id='$id'");
if (mysqli_num_rows($result) == 0) {
echo 'That id is not valid!';
}
else {
// Set up an array for the items
while($row = mysqli_fetch_array($result))
{
$source = $row['source'];
}
$items = array(
"id" => $id,
"source" => $source,
);
var_dump($items);
$_SESSION['items'] = $items;
}
}
?>
$items = array();
,以确保安全。 - Seth Malaki