简体   繁体   中英

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. The user will input a user and id number in a form and then that information will be sent to my php script. 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'. 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'). 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.

在此输入图像描述

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. 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) . 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. 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. 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:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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