R
R
Rumus Bin2016-09-26 17:01:09
PHP
Rumus Bin, 2016-09-26 17:01:09

How to iterate over two php arrays at once?

Good day. I'm still learning the basics of php!
In solving the problem, I came to the need to sort through two arrays ... it's better to explain with an example:
The essence of the question is this -
two arrays get into the model, one with id ($data_id) the other with phone numbers ($data_numbers).
index arrays, the value in the $data_id[0] array corresponds to the value in the array ($data_numbers[0]).
It is necessary to write phone numbers in the database in the appropriate tables according to their id
(well, it seems to be clear.)
I didn’t think of anything better how to iterate through these arrays with two nested foreach loops, assigning their values ​​to variables and creating a query to the database each time, here is the code:

foreach ($data_id as $id){
            foreach ($data_numbers as $number){
                $db = Db::getConnection();
                $sql = 'UPDATE phone_numbers SET phone_number = :number '
                . 'WHERE id = :id';
        
                $result = $db->prepare($sql);
                $result->bindParam(':number', $number, PDO::PARAM_INT);
                $result->bindParam(':id', $id, PDO::PARAM_INT);
                
                return $result->execute();
            }
        }

But the idea failed (as you understand) only the first element is recorded in the database, the rest are ignored.
How can such an idea be brought to life?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SharuPoNemnogu, 2016-09-26
@RumusBin

you have a return, so it comes out after the first element, remove it.
take prepare out of the loop, put it in front of it, why do the same thing every time.
you can make one array through the array_combine function, you get an id => number array, well, or as Maxim Timofeev suggested.
bindParam binds a reference to a variable, bindValue - the value of the variable, which is more relevant here

M
Maxim Timofeev, 2016-09-26
@webinar

foreach ($data_id as $key=>$id){
$id; //это первый массив
$data_numbers[$key]; //это второй массив
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question