简体   繁体   中英

PHP associative array foreach

I need to loop over the following array but we can assume that the array can be empty in some cases:

Array
    (
    [0] => Array
        (
            [AA562-FS] => 521502151
        )

    [1] => Array
        (
            [FF-25166] => 66326262
        )
)

The first value is an ID and the other one is a number, I have an input of these two from another source, I need to loop over the array and if the ID is equal to the one i have from another source and its value the number is not equal to the one from the source i need to replace the number.

Otherwise I just add on to the existing array, but im having some issues right now, this is what i have so far:

 public function addToken($array1, $source_id, $source_number)
{
    if (!empty($array1)) {
        foreach ($array1 as $array) {
            if ($array[0] == $source_id && $array[1] !== $source_number) {
                $array1[1] = $source_number;
            }
        }
    }
    $new_array = json_encode($array1, 1);
}

Still need to figure out how to add on the values if its not equal $array[0] !== $source_id

Would it be better to build the array as following?

Array
    (
    [0] => Array
        (
            [id] => AA562-FS
            [number] => 521502151
        )

    [1] => Array
        (
            [id] => AAAD-wwww
            [number] => 1166777
        )
)

You're overcomplicating the array structure. You should build your array like this.

Array
(
        [AA562-FS] => 521502151
        [FF-25166] => 66326262
) 

This simplifies the code you need to update it:

 public function addToken($array1, $source_id, $source_number)
{
    // Assign the source number to the array element. 
    // If the array element does not exist it's created.
    // If it does exist, the source number is updated. 
    // (If the number is the same it's updated to the same number - OK!)

    $array1[$source_id] = $source_number;
    return $array1;
}

You can use a foreach ($array as $index => $value) loop, using the first array format you wrote. It will iterate on each element of your array, and in each iteration, the $index variable will correspond to your 'ID', and the $value variable to the value.

In your case it would look like this:

foreach ($array1 as $index => $value) {
    if ($index == $source_id && $value !== $source_number) {
        $array1[$index] = $source_number;
    }
}

Edit: if you want to add the value $source_number to the key $source_id in your array if it does not exists, the following function should do the trick:

public function addToken($array1, $source_id, $source_number)
{
    if (!empty($array1)) {
        foreach ($array1 as $index => $value) {
            if ($index == $source_id && $value !== $source_number) {
                $array1[$index] = $source_number;
            }
        }
        /* After you looped through your array, 
         * check if the id $source_id exists or not, and if not, 
         * insert it in your array:
         */
        if (!array_key_exists($source_id, $array1)) {
            $array1[$source_id] = $source_number;
        }
    }
    $new_array = json_encode($array1, 1);
}

Firstly, I'm assuming that you are passing in the array shown at the top of your question. Which will therefore be in the form:

$array = [
    ['AA' => 111],
    ['AB' => 111],
    ['AC' => 111],
    ['AD' => 111],
    ['AE' => 111],
    ['AA' => 112]
];

Assuming that that is correct then your if statement does not work:

$array[0] == $source_id && $array[1] !== $source_number

// $array[0] && $array[1] simply don't exist! Referencing them should
// throw a notice in PHP...


// In the first foreach loop $array looks as follows

$array = ['AA' => 111];

// In the second loop it will be

$array = ['AB' => 111];

// and so on through the array. The index, in this case, is AA, AB, AC etc.
// the indexes 0 and 1 just don't exist

That being the case we can begin to fix your code by modifying the if statement to:

key($array) == $source_id && current($array) !== $source_number

Of course we also need to update these two lines:

foreach ($array1 as $array)

$array1[1] = $source_number;

To:

foreach ($array1 as &$array)

$array = [$source_id => $source_number];

So, your code is now partially working; if we call the function it will update existing ID values however it won't add new ones...

// Notice we pass $array by reference( & ) so that it updates the original array
// if you prefer not to do this then, obviously, you need to return the updated array

function addToken(&$array, $source_id, $source_number)
{
    if (!empty($array)) {
        foreach ($array as &$arr) {
            if(key($arr) == $source_id && current($arr) != $source_number) {
                $arr = [$source_id => $source_number];
            }
        }
    }
}

addToken($array, "AB", 112);

// Updated array...
$array = [
    ['AA' => 111],
    ['AB' => 112],
    ['AC' => 111],
    ['AD' => 111],
    ['AE' => 111],
    ['AA' => 112]
];

Adding an item if it doesn't exist

To do this we need to firstly look though the entire array to see if there is a match and if there isn't, at the end, then we add a new item.

function addToken(&$array, $source_id, $source_number)
{
    if(!empty($array)){
        $tokenExists = false;
        foreach($array as &$arr){
            if(key($arr) == $source_id){
                $arr = [$source_id => $source_number];
                $tokenExists = true;
            }
        }

        if(!$tokenExists){
            $array[] = [$source_id => $source_number];
        }
    }
}

Notice, we don't need to check whether the value matches $source_number , we just update the value to $source_number either way we have the same result.


However unless you have duplicates in your input array (as shown, purposefully in the example I've used above) where an ID in the original array could have multiple values that all need to be updated to the new one. There is no need for any of this @TP has the right idea!

Simplify the format to:

$array = [
    'AA' => 111, // Note this value is effectively overwritten by the last line of the arrray, you can't have duplicate keys
    'AB' => 111,
    'AC' => 111,
    'AD' => 111,
    'AE' => 111,
    'AA' => 112
];

function addToken(&$array, $source_id, $source_number)
{
    $array[$source_id] = $source_number;
}

Although, with this simplified array... Do you even need to put the update in a function/method? I guess that depends on the rest of your code.

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