Home > Enterprise >  extract set of values from multidimensional array using an index
extract set of values from multidimensional array using an index

Time:11-15

I've a standard array which only contains a list of IDs and I have a multidimensional array which contains a set of values (ID, name, surname). What I'm trying to do is to extract from the multidimensional array the whole set of values only for the IDs present in the first array. Example:

    $array1 = "1","2","12","43","52";

    $array2 = {[0]"id"=>"12","name"=>"Robert","surname"=>"Plant";[1]"id"=>"43","name"=>"Jimmy","surname"=>"Page";[2]"id"=>"8","name"=>"Mary","surname"=>"Stilton";}

I need to get an array which contains

    {[0]"id"=>"12","name"=>"Robert","surname"=>"Plant";[1]"id"=>"43","name"=>"Jimmy","surname"=>"Page";}

I've tried different solutions, using a foreach cycle, but I'm not getting the required output.

What I've tried: $idpresent is the array with the IDs list, $globalarray is the multidimensional array.

foreach($idpresent as $test){
    if(in_array($test,$globalarray["id"])){
        echo $globalarray["name"];
    }
}

But I'm getting no output. Can anybody kindly help?

CodePudding user response:

Following logic might help you on your way: cycle through the whitelist ($array1) and if id is present in $array2 store the resulting record in $result array.

<?php
$array1 = ["1","2","12","43","52"];

$array2 = [
    ["id"=>"12","name"=>"Robert","surname"=>"Plant"],
    ["id"=>"43","name"=>"Jimmy","surname"=>"Page"],
    ["id"=>"8","name"=>"Mary","surname"=>"Stilton"]
    ];

$result = []; // result store
foreach($array1 as $whitelisted) {
    foreach($array2 as $record) {
        if($record['id'] == $whitelisted) $result[] = $record;
    }
}

working demo

  •  Tags:  
  • php
  • Related