gpt4 book ai didi

php - 将项目添加到数组

转载 作者:行者123 更新时间:2023-12-05 05:27:20 25 4
gpt4 key购买 nike

我对 PHP 数组的了解有限。我读过 PHP Arrays - Manual , 但它并没有以足够的值(value)解释这一点,让我诚实地理解它。

我在 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 调用此函数,创建的数组的 ID 为 1和来源 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 Aitem B到同一个数组并将它们定义为单独的项目?

那么基本上我该怎么做呢?

array {
item A {
id => 1
source => foo
}
item B {
id => 2
source => boo
}
}

并且只需在添加项目时构建数组。我在 session 中保存数组,这有助于在每次调用函数时检索数组并将其添加到数组吗?

只是为了额外的帮助,我的完整 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;
}
}
?>

最佳答案

来自documentation :

array_push — Push one or more elements onto the end of array

...具有相同的效果:

$array[] = $var;

让我们将其应用到您的案例中:

$items = array(); // Has to be initialised first, somewhere in your code
// ....
// Then after your while loop
$new_item = array("id" => $id, "source" => $source);

array_push($items, $new_item); // Append $new_item inside $items as its last value.

关于php - 将项目添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com