简体   繁体   English

如何在PHP中向多维数组添加元素?

[英]How add elements to a multidimensional array in PHP?

I have been doing some research on this issue on this forum and others online, but I just cannot seem to figure it out. 我一直在这个论坛和其他网上对这个问题进行一些研究,但我似乎无法弄明白。

My goal with one of the functions in my code is to add 5 karma points to an existing user or create a new user with a karma score of '1' if the user is not there. 我的代码中的一个函数的目标是向现有用户添加5个业力点,或者如果用户不在那里,则创建业力得分为“1”的新用户。 The user will input a user and id number in a form and then that information will be sent to my php script. 用户将在表单中输入用户和ID号,然后该信息将发送到我的PHP脚本。 That function uses that information to do its magic, but the output is wrong. 该函数使用该信息来实现其魔力,但输出错误。

What I get is a new user with a karma score of '6'. 我得到的是一个业力得分为“6”的新用户。 I left out some of the script which is extraneous to this matter. 我遗漏了一些与此事无关的剧本。

Any help or advice will be greatly appreciated. 任何帮助或建议将不胜感激。

<html>

<head></head>

<body>
<div align="center">
<?php

// Array begin 
$karma_score = array(   array("Userid" => 1, "NameID" => 'Doe', "Karma" => 45, "LastLogin" => "2012-08-30"),
                        array("Userid" => 2, "NameID" => 'Smith', "Karma" => 123, "LastLogin" => "2012-09-02"),
                        array("Userid" => 3, "NameID" => 'Chan', "Karma" => 1, "LastLogin" => "2011-12-23"),
                        array("Userid" => 4, "NameID" => 'Zee', "Karma" => 15, "LastLogin" => "2012-07-01"));

// Counter for amount of users
$counter = count($karma_score);

// Function to print general array
function printArray($a){
    echo '<table border="1px">';
    echo '<tr>';
        foreach(array_keys($a[0]) as $head){
            echo '<th>'.$head.'</th>';
        }
    echo '</tr>';

    foreach($a as $b) {
    echo '<tr>';
        echo '<td>'.$b['Userid'].'</td>';
        echo '<td>'.$b['NameID'].'</td>';
        echo '<td>'.$b['Karma'].'</td>';
        echo '<td>'.$b['LastLogin'].'</td>';
    echo '</tr>';
    }
    echo '</table>';
}

echo '<br>';

function findInfo()
{
    global $karma_score;
    $counter = count($karma_score);

        foreach ($karma_score as $key => $b) {
            if ($b['NameID'] === $_POST['name'])
                $karma_score[$key]["Karma"] += 5;
            else 
                $karma_score[$counter+1] = array("Userid" => $_POST['id'], "NameID" => $_POST['name'], "Karma" => 1, "LastLogin" => date("Y-m-d"));     
        }
    echo "<br> Here is your updated table.";
    printArray($karma_score);
}

if (isset($_POST['submit'])) {
    findInfo();
}

?>

<br>


Please enter name and id. If name exists, add 5. If not, add user.
<form action="" method="POST">
    Name: <input type="text" name="name" placeholder="Enter Name Here">
    ID: <input type="text" name="id" placeholder="Enter ID #">
    <input type="submit" name="submit">


</div>
</body>

</html>

Below is my output: The fourth table is what I get when i click submit (the user I entered is 'Alec' and the id I entered is '5'). 下面是我的输出:第四个表是我点击提交时得到的(我输入的用户是'Alec',我输入的ID是'5')。 Thank you in advance! 先感谢您!

在此输入图像描述

EDIT: This is what happens when I submit a user already in the array. 编辑:当我提交已经在数组中的用户时会发生这种情况。 The outcome I want is a simple plus 5 karma score for the user. 我想要的结果是用户的简单加5业力分数。

在此输入图像描述

Absolutely, your looping is always compare NameID and if not match, you add element to array, whereas values of element NameID in is not always same to your value looking for. 当然,循环总是比较NameID ,如果不匹配,则将元素添加到数组,而元素NameID in的值并不总是与您查找的值相同。 in your looping has added 3 times to element array (in value thats not match to your value compare, in case, you submit exist value) with same key[5] ($count + 1) . 在你的循环中已经添加了3次元素数组(值与你的值不匹配,以防你提交现有值)与相同的键[5] ($count + 1) so you can create variable thats indicated your value submit is exist. 所以你可以创建表明你提交的值存在的变量。

function findInfo(){
    global $karma_score;
    $counter = count($karma_score);
    $isExist = false;
    foreach ($karma_score as $key => $b) {
        if ($b['NameID'] === $_POST['name']){
            $karma_score[$key]["Karma"] += 5;
            $isExist = true;
        }
    }
    if(!isExist)
        $karma_score[$counter+1] = array("Userid" => $_POST['id'], "NameID" => $_POST['name'], "Karma" => 1, "LastLogin" => date("Y-m-d"));     
    echo "<br> Here is your updated table.";
    printArray($karma_score);
}

Since the first tier of your array has only a numeric index... You'd increment a row like so: 由于数组的第一层只有一个数字索引......你会增加一行,如下所示:

$karma_score[0]['Karma'] += 5;

...but that's obviously a bit volatile. ......但这显然有点不稳定。 You may want to use the UserID number for a distinct array key. 您可能希望将UserID编号用于不同的数组键。 Then you can easily increment a given user's karma. 然后,您可以轻松增加给定用户的业力。 Like so: 像这样:

$karma_score = array(   
    1 => array("Userid" => 1, "NameID" => 'Doe', "Karma" => 45, "LastLogin" => "2012-08-30"),
    2 => array("Userid" => 2, "NameID" => 'Smith', "Karma" => 123, "LastLogin" => "2012-09-02"),
    3 => array("Userid" => 3, "NameID" => 'Chan', "Karma" => 1, "LastLogin" => "2011-12-23"),
    4 => array("Userid" => 4, "NameID" => 'Zee', "Karma" => 15, "LastLogin" => "2012-07-01"));

If you did that, then you could for example; 如果你这样做,那你可以举例说;

$karma_score[4]['Karma'] += 5; // Would increment Zee's karma

...without looping all over the place trying to find a row that matches the user's ID. ...没有遍布整个地方试图找到与用户ID相匹配的行。 But that's getting pretty clunky there. 但那里的相当笨重。 You might consider tossing all of this data into a database at some point. 您可能会考虑在某个时刻将所有这些数据丢弃到数据库中。 You could also: 你也可以:

$karma_score['Zee']['Karma'] += 5;

...and really get rid of that unnecessary loop. ......真的摆脱了那个不必要的循环。 Creating problems for you, will create more problems for you... A bit of logic clean-up due for the code, bro. 为您创建问题,将为您创造更多问题......由于代码,兄弟会进行一些逻辑清理。 :) :)

Your problem was in: 你的问题是:

foreach ($karma_score as $key => $b) {
    if ($b['NameID'] === $_POST['name'])
        $karma_score[$key]["Karma"] += 5;
    else 
        $karma_score[$counter+1] = array("Userid" => $_POST['id'], "NameID" => $_POST['name'], "Karma" => 1, "LastLogin" => date("Y-m-d"));     
}

You don't need a foreach, try with my code: 你不需要foreach,试试我的代码:

<html>

<head></head>

<body>
<div align="center">
<?php

// Array begin 
$karma_score = array(   array("Userid" => 1, "NameID" => 'Doe', "Karma" => 45, "LastLogin" => "2012-08-30"),
                        array("Userid" => 2, "NameID" => 'Smith', "Karma" => 123, "LastLogin" => "2012-09-02"),
                        array("Userid" => 3, "NameID" => 'Chan', "Karma" => 1, "LastLogin" => "2011-12-23"),
                        array("Userid" => 4, "NameID" => 'Zee', "Karma" => 15, "LastLogin" => "2012-07-01"));

// Counter for amount of users
$counter = count($karma_score);

// Function to print general array
function printArray($a){
    echo '<table border="1px">';
    echo '<tr>';
        foreach(array_keys($a[0]) as $head){
            echo '<th>'.$head.'</th>';
        }
    echo '</tr>';

    foreach($a as $b) {
    echo '<tr>';
        echo '<td>'.$b['Userid'].'</td>';
        echo '<td>'.$b['NameID'].'</td>';
        echo '<td>'.$b['Karma'].'</td>';
        echo '<td>'.$b['LastLogin'].'</td>';
    echo '</tr>';
    }
    echo '</table>';
}

echo '<br>';

function findInfo()
{
    global $karma_score;
    $counter = count($karma_score);

    //if php>5.5.0 use $names = array_column($karma_score, 'NameID');
    $names = array_map(function($element){return $element['NameID'];}, $karma_score);
    if(in_array($_POST['name'], $names)) {
       $key = array_search($_POST['name'], $names);
       $karma_score[$key]['Karma'] += 5;
    } else {
      $karma_score[$counter] = array("Userid" => $_POST['id'], "NameID" => $_POST['name'], "Karma" => 1, "LastLogin" => date("Y-m-d"));             
    }       

    echo "<br> Here is your updated table.";
    printArray($karma_score);
}

if (isset($_POST['submit'])) {
    findInfo();
}

?>

<br>


Please enter name and id. If name exists, add 5. If not, add user.
<form action="" method="POST">
    Name: <input type="text" name="name" placeholder="Enter Name Here">
    ID: <input type="text" name="id" placeholder="Enter ID #">
    <input type="submit" name="submit">


</div>
</body>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM