Naveed Sheriffdeen
Naveed Sheriffdeen

Reputation: 980

php array looping through two arrays with different indexes

I have two arrays,one containing a list of names (array name = canNAMES),

["name 1","name 2","name 3"];

the first array has around 70 values within, And my second array has around 600 objects within it (array name=data),

[
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name n",
    "rate": "£30.00",
    "hours": 32,
    "exp": null,
    "net": "£960.00",
    "vat": "£192.00",
    "gross": "£1,152.00"
},
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name n",
    "rate": "£25.00",
    "hours": 30,
    "exp": null,
    "net": "£750.00",
    "vat": "£150.00",
    "gross": "£900.00"
}
]

I am trying to use php in_array function to get the objects that has the names listed in the first array out.

when I use it as below I am able to get the required results but it only reads up-to 70 records

foreach ($canNAMES as $index => $row) {
    if (in_array($row, (array) $data[$index]["contractor"])) {
        $MAIN[] = $data[$index];
    }
}

The above code is where i loop through the first array(canNAMES array) that has 70 records. when i try looping through the second array(data array) i get an undefined offset error as the first array doesn't have a index above 69.

My question is how to solve this issue, is there a better way to do what i am trying.

Thanks

Upvotes: 0

Views: 111

Answers (2)

dWinder
dWinder

Reputation: 11642

I guess you want all the element in the data array that have a name that exist in the canNAMES array.

Consider the following:

$canNAMES = ["ccc","bbb","eee"];
$data = json_decode('[{"id":1, "contractor": "aaa"}, {"id":2, "contractor": "ddd"}, {"id":3, "contractor": "ccc"}, {"id":4, "contractor": "bbb"}]');
$res = array();

foreach($data as $elem) {
    if (in_array($elem->contractor, $canNAMES))
        $res[] = $elem;
}

echo print_r($res);
return;

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57131

If the names aren't unique then you can easily just loop through each sets of data matching one against the other...

$canNAMES = ["name 1","name 2","name 3"];

$data = json_decode ('[
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name 3",
    "rate": "£30.00",
    "hours": 32,
    "exp": null,
    "net": "£960.00",
    "vat": "£192.00",
    "gross": "£1,152.00"
},
{
    "agency": "test agency",
    "work_end": "21-Oct",
    "contractor": "name 1",
    "rate": "£25.00",
    "hours": 30,
    "exp": null,
    "net": "£750.00",
    "vat": "£150.00",
    "gross": "£900.00"
}
]');

foreach ( $canNAMES as $name )  {
    foreach ( $data as $entry ) {
        if ( $name == $entry->contractor )    {
            print_r($entry);
        }
    }
}

Upvotes: 1

Related Questions