我对 PHP 数组的了解有限。我已经阅读了PHP Arrays - Manual,但它并没有以足够的价值解释这一点,让我无法诚实地掌握它。
我在一份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
,则将使用 id1
和 source创建数组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;
}
}
?>