S
S
Sergey Zelensky2015-07-13 14:55:23
PHP
Sergey Zelensky, 2015-07-13 14:55:23

How to compare php arrays?

there is a function that is called in a loop and makes an array of the form

array('a1'=>array(....),'a2'=>array(....) ...'aN'=>array(....));

so this function is called, for example, 5 times, and I need to compare each array that it made with the rest and bring them to their form (i.e. if there is a key in others, then add it to the current one, and set the value to 0)
I will not forgive write a solution, just share your experience, the only thing that came to my mind was to make a buffer (array), and each time the function is called, write the created array there, and then use this buffer to check them, but somehow it turns out to be very resource-intensive, tell me the methods solutions

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2015-07-13
@SergeyZelensky-Rostov

The algorithm is as follows:
1. Iterate all 5 arrays, write the keys to a separate array.
2. Throw away all non-unique keys.
3. Iterate this separate array and inside the loop check for the presence of a key in each of the 5 arrays, if there is no key, add it with a default value.

L
Lesha Kiselev, 2015-07-13
@Yakud

function fill_array_diff(array $array1, array $array2) {
    $diff = array_keys(array_diff_key($array1, $array2));

    return array_merge($array2, array_fill_keys($diff, 0));
}

// Массив с которым сравниваем
$mainArray = ['a1' => 100, 'a2' => 200, 'a100' => 300, 'a200' => 400];

// Массив который сравниваем
$array = ['a1' => 1,'a2' => 2, 'a3' => 3];

$array = fill_array_diff($mainArray, $array);

var_export($array);
/*
array (
'a1' => 1,
  'a2' => 2,
  'a3' => 3,
  'a100' => 0,
  'a200' => 0,
)*/

S
skvot, 2015-07-13
@skvot

Just comparison by comparison operator?
array_diff() ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question