将项目添加到数组

3

我的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 Aitem 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;
        }
    }
?>
4个回答

2

根据文档

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.

0

首先做这个:

$items = []; // It's a good practice to initialize first
while($row = mysqli_fetch_array($result))
{
    $items[] = [ // Append to end of array
       "id" => $id,
       "source" => $row['source'], // Key with source
    ];
}
 // Here if you var_dump($items) you will see the result

这样是可以的,但你还需要在某个地方初始化$items,例如 $items = array();,以确保安全。 - Seth Malaki
这看起来可能可行,虽然我讨厌被喂饱,我不会只是复制粘贴。请在您的代码答案中解释。提前感谢! :) - user2948950

0
while($row = mysqli_fetch_array($result))
{
    $source = $row['source'];
    $items = array(
        "id"     => $id,
        "source" => $source,
    );
    $_SESSION['items'][] = $items;
}

Multi - dimensional array

你可能想要在 $_SESSION['items'] 中存储另一个数组,这将使其成为多维数组。

[] 将把下一个值堆叠到下一个可用键中。

这意味着 $item 的第一个值将被存储在 $_SESSION['items'][0] 中,$item 的第二个值将被存储在 $_SESSION['items'][1] 中,以此类推...


这看起来可能行得通,尽管我讨厌被喂食,我不会只是复制和粘贴。请在您的代码答案中解释。提前谢谢! :) - user2948950
我添加了一些解释,但为了更好地理解,我建议您在谷歌上寻找更好的多维数组教程。有很多可用的教程。 - Prince Singh
这似乎没有构建。我添加了一个foreach方法来回显每个数组。http://alphahq.org/shop/config/functions/shopping-functions.php?action=add&id=65 请单击,然后将65更改为25,您就会明白我的意思。 - user2948950
你的意思是什么?我在我的代码中添加了:foreach ($_SESSION['items'] as $key) { echo "
" .$id. " is equal to the source: " .$source. "
"; },但我只看到当前在URL中获取的ID,而不是之前输入的所有ID列表。
- user2948950
当你只喂一次时,你如何期望数组中有多个值?检查我的更新答案,你可能会得到你所犯错误的提示。 - Prince Singh
显示剩余2条评论

0

针对这个案例

// Based on pr1nc3's answer
$_SESSION['items'] = array(); // Create a new array

foreach($myResult as $row)
    $_SESSION['items'][] = $row;

[] 是这里的魔法:它告诉 PHP “取出前面标识的数组并将此项推入其中” - 实际上,这本质上是 array_push 方法的简写:

$a = $b = array();
$c = array(1, 2, 3, 4, 5, 6);

foreach($c as $value) {
    $a[] = $value;
    array_push($b, $value);
}

在上述操作之后,$a$b 在调用 var_dump 函数时将会显示相同的结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接