0

Is there a way to join two arrays based upon a same value in a key? As an example in MySQL you can left join two tables when two fields have the same value in it.

The first array called 'phoneArr' is one with a person_id and a phone number The second array called 'clientDate' is one with a person_id and a appointment date.

Here are the arrays:

$phoneArr = array();

$phoneArr[0]['person_id'] = "123456";
$phoneArr[0]['phone'] = "555-2222";

$phoneArr[1]['person_id'] = "7654321";
$phoneArr[1]['phone'] = "555-1111";


$clientDate = array();
$clientDate[0]['person_id'] = "123456";
$clientDate[0]['date_time'] = "01-07-13 13:00";

$clientDate[1]['person_id'] = "7654321";
$clientDate[1]['date_time'] = "01-07-13 10:30";

Now if the person id in clientDate will always exist in the phoneArr, but not the other wat around. The persons in the phoneArr do not always exist in the clientDate.

What I want is to get a match of these arrays where I will be left with a new array with the info of both arrays, but only of there is a match on the 'person_id'.

Is this doable without MySQL?

1 Answer 1

2

If you are going to look up data by a key value, and that key value is unique over the table, you might consider using that as the array key, so your $phoneArr would be set up as:

$phoneArr["123456"]['phone'] = "555-2222";
$phoneArr["7654321"]['phone'] = "555-1111";

Do the same with the other array

Then you can:

foreach ($phoneArr AS $id=>$record) {
    if (array_key_exists($id,$clientDate)) {
         //  the client id is $id, $record has their phone #, and $clientDate[$id] has their date/time
         // do something with it here - either process it (preferable) or put the data in another array.
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great I am going to look into that. I need to make some changes elsewhere, since I don't type out these arrays in my script, but create them with a for loop as well.

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.