N
N
Nikelamoc2015-09-22 00:23:14
PHP
Nikelamoc, 2015-09-22 00:23:14

How to process 2 arrays less resource-intensive?

Good afternoon.
There are 2 arrays
$array_first and $array_second
I need to pull out all the values ​​that are in both arrays + their keys.
Now it is solved like this

foreach($array_first as $key => $value)
  {
  if (in_array($value, $array_second, true))
    {
    $key_second = array_search($value, $array_second);

    // тут засовываем все в отдельный массив

    }

How can this whole comparison be made more reasonable?
I tried using array merge, nothing came out (
I don’t need a code, just poke in the direction where to think .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2015-09-22
@Nikelamoc

array_intersect_assoc
// EDIT

<?php

$foo = [
    'alice' => 'bob',
    'bar' => 'baz',
];

$bar = [
    'john' => 'doe',
    'foo' => 'baz',
];

var_dump(
    array_intersect($foo, $bar),
    array_intersect($bar, $foo)
);

// output:
array(1) {
  'bar' =>
  string(3) "baz"
}
array(1) {
  'foo' =>
  string(3) "baz"
}

S
Sergey Sokolov, 2015-09-22
@sergiks

Sort each array by value; move through both arrays, catching matching values ​​and their keys.
And sorting can be done with minimal memory cost, in chunks. And the second phase, comparison - it is enough to store the current values ​​of each of the arrays in memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question