PHP在键值上匹配两个数组(例如mysql join) [英] PHP Match two arrays on key value (like mysql join)

查看:219
本文介绍了PHP在键值上匹配两个数组(例如mysql join)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以基于键中的相同值来连接两个数组? 例如,在MySQL中,当两个字段中的值相同时,您可以保留两个表的连接.

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.

第一个名为"phoneArr"的数组是一个具有person_id和电话号码的数组 第二个名为"clientDate"的数组是一个带有person_id和约会日期的数组.

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.

这是数组:

$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";

现在,如果clientDate中的人员ID将始终存在于phoneArr中,而周围的其他人员则不存在. phoneArr中的人员并不总是存在于clientDate中.

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.

我想要得到的是这些数组的匹配项,在那里我将得到一个包含两个数组的信息的新数组,但只有'person_id'上存在一个匹配项.

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'.

在没有MySQL的情况下可以做到吗?

Is this doable without MySQL?

推荐答案

如果您要通过键值查找数据,并且该键值在表中是唯一的,则可以考虑将其用作数组键,因此您的$ phoneArr将设置为:

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

那么您可以:

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.
     }
}

这篇关于PHP在键值上匹配两个数组(例如mysql join)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆