Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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
        )
)
question from:https://stackoverflow.com/questions/65835437/php-associative-array-foreach

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...