0

I have two arrays, the second is multidimensional. I'm trying to return a third array where the host_id in Array2 match the values in Array1.

Array1 
(
    [0] => 146
    [1] => 173
)

Array2
(
    'localhost' => (
        '0' => (
            'host_id' => 146
        ),
    ),
    '192.168.0.43' => (
        '1' => (
            'host_id' => 160
        ),
    ),
    '192.168.0.38' => (
        '2' => (
            'host_id' => 173
        )
    )
)

So Array3 should be:

    Array3
    (
        [localhost] => Array
            '0' => (
                'host_id' => 146
            ),

        [192.168.0.38] => Array
            '0' => (
                'host_id' => 173
            ),

    )

I have tried this, but it's only returning the last matched host_id.

foreach ($Array1 as $value) {   

    $filtered_hosts = array_filter($Array2, function ($host) use ($value) {

        return in_array($host['host_id'], $host_id);
    });
}

What am I missing?

3
  • 1
    you're overwriting $filtered_hosts in foreach... you want to push to $filtered_hosts instead Commented Nov 7, 2018 at 20:12
  • 1
    Hi a better solution would be to use with array_filter, in_array. Try it out. Commented Nov 7, 2018 at 20:13
  • Thanks ankabout, changing my return statement to this solved my problem. return in_array($host['host_id'], $value); Commented Nov 7, 2018 at 20:27

1 Answer 1

3

You could just use array_filter without the foreach.

Pass the first array to use($array1) and use in_array to check if the value for 'host_id' exists.

$array1 = [
  146,
  173
];

$array2 = [
    'localhost' => [
        'host_id' => 146
    ],
    '192.168.0.43' => [
        'host_id' => 160
    ],
    '192.168.0.38' => [
        'host_id' => 173
    ]
];

$filtered_hosts = array_filter($array2, function($x) use ($array1) {
    return in_array($x['host_id'], $array1);
});


print_r($filtered_hosts);

Demo

Update

For the updated data structure you could get the first item from the subarray with for example reset:

$filtered_hosts = array_filter($array2, function ($x) use ($array1) {
    return in_array(reset($x)['host_id'], $array1);
});

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, changing my return statement to use in_array gave me the desired result.
What if you add another dimension to the array? $Array2 = [ 'localhost' => [ '0' => [ 'host_id' => 146 ], ], '192.168.0.43' => [ '1' => [ 'host_id' => 160 ], ], '192.168.0.38' => [ '2' => [ 'host_id' => 173 ] ] ];
@JoshForcier You have changed your original question. Do you mean like this 3v4l.org/AMHda

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.