PHP Match two arrays on key value (like mysql join) - php

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?

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

Related

How to reduce the results from one-to-many join query into a signle object for each "one"?

Suppose I have 2 tables:
Applicants:
- id
- full_name
- address
Educations:
- id
- applicant_id
- institute
- address
After I did an inner join, I want to loop through the data on a template. But first I want to convert all educational records for an applicant into an array and attach it to the applicant record.
applicant_a:
- id
- full_name
- address
- educations: [ OBJECTS HERE ]
What's the way to do so? Can I do it on the database side via SQL? Or do I have to do it on PHP side?
This is a simple draft of how I would do it in your case.
I'm not saying this is the best or even the only way to do it.
This specific is not tested, though I used that logic often before.
Note, that this is only about the logic here.... but this should give you what you want!
$applicants = array();
$old_applicant_id=null;
while ($row=$db->fetch()) {
// new applicant
if($row['applicant_id']!=$old_applicant_id) {
// save the education to the old one - if there is one
if(isset($applicant)) {
$applicant['education'] = $educations;
$applicants[] = $applicant;
}
// then (and in first round)
$applicant = array();
$applicant['fullName'] = $row['fullName'];
// repeat for other values of applicant
$educations = array(); // initialize educations
$education = array();
$education['id'] = $row['edu_id'];
// repeat for institute, etc
$educations[] = $education;
} else {
// already existing applicant, so only add education
$education = array();
$education['id'] = $row['edu_id'];
// repeat for institute, etc
$educations[] = $education;
}
// set old applicant
$old_applicant_id = $row['applicant_id'];
}
// finally you have to save the last one to the array
$applicant['education'] = $educations;
$applicants[] = $applicant;
Another way would be to have two seperate queries and merge them in two loops.
This question of mine was related. I was asking about the spead of the two versions. Might be interesting.
MySQL does not return arrays, so this kind of thing is usually best done in client code (in this case PHP).
But if you are just going to concatenate the educations into a string of some sort you may want to look into the GROUP_CONCAT aggregate function.

Laravel Query Builder select a column with multiple values

I have four arrays and a one variable like below.
$jptypes = ["26","27"]
$jvalues = ["57","62"]
$jbranches = ["33","63"]
$jstream = ["2","2"]
$jmarks = 10
I want to collect employees with those matching arrays and value.
$empsarr = DB::table('otc_employee_qualifications')
->whereIn('emp_qualifctn_type',$jptypes)
->whereIn('qualification_value',$jvalues)
->whereIn('emp_qualifctn_branch',$jbranches)
->whereIn('emp_qualifctn_stream',$jstream)
->where('qualification_mark','>=',$jmarks)
->distinct()
->lists('employee_id');
return $empsarr;
But whereIn method will not checking both values. its in OR case.
I want to check both the values in the array at once.
how can i solve this issue ?

Mysql to Json. Can this be solved using MySQL?

I have a MySQL query that will be converted to JSON and used in Obj C for each user with a specific id. I believe that this is a MySQL puzzle, but there may be an answer in JSON. I don't ask many questions, so I'll try to make it concise.
Here is a screen shot of values for one user. If you notice, the field_id may vary because not all info is required, so the id field will vary from 3 to 8 values for a given user_id:
I have to make a query where the results GROUP BY column1 (user_id), but only WHERE column2 (field_id) has the following values field_id='18' and field='19', Then (THE BIG PROBLEM) I need to populate the results in one GROUP with both values of column3 (value) so I can get results in one JSON object.
I already know how to convert to JSON for use in iOS, but I can only get it to give me results as two objects.
My current query
$query = "SELECT * FROM table1 WHERE field_id='18' OR field_id='19' ORDER BY user_id ";
Current Result
[{"id":"5","user_id":"461","field_id":"18","value":"1_MX4zNjcxNzM5Mn4x...","access":"0"},
{"id":"6","user_id":"461","field_id":"19","value":"T1==cGFydG5lcl9pZD0...","access":"0"},
{"id":"11","user_id":"463","field_id":"18","value":"1_MX4zNjcxNzM...","access":"0"},
{"id":"12","user_id":"463","field_id":"19","value":"T1==cGFydG5lcl9...","access":"0"}]
I need the two JSON objects with matching user_id fields as one object with results that differentiate field='18' value from field='19' value. Something like:
[{"id":"5","user_id":"461","field_id":"18","value18":"1_MX4zNjcxNzM5Mn4x...","value19":"T1==cGFydG5lcl9pZD0...","access":"0"},
{"id":"11","user_id":"463","field_id":"18","value18":"1_MX4zNjcxNzM...","value19":"T1==cGFydG5lcl9...","access":"0"}]
OR
[{"id":"5","user_id":"461","field_id='18'":"1_MX4zNjcxNzM5Mn4x...","field='19'":"T1==cGFydG5lcl9pZD0...","access":"0"},
{"id":"11","user_id":"463","field_id='18'":"1_MX4zNjcxNzM...","field='19'":"T1==cGFydG5lcl9...","access":"0"}]
THANKS...
I'm not 100% sure if this will work. I cannot easily try the JSON output of it. But what if you run a query like this?
SELECT id, user_id,
GROUP_CONCAT(field_id,':',value) field_id,
access
FROM table1 WHERE field_id='18' OR field_id='19'
GROUP BY user_id
ORDER BY user_id
You probably want to to look at handling this in PHP when reading in the result set.
So use your current query of
SELECT * FROM table1 WHERE field_id='18' OR field_id='19' ORDER BY user_id
But build result data object like this:
$results = array();
$i = -1;
$current_user_id = '';
while ($row = [YOUR MySQL FETCH MECHANISM HERE]) {
// determine if this record represents a new user id in the result set
// if so, we need to set up the user object and start another entry in top level array
if($current_user_id != $row['user_id']) {
// you have moved to a new user in the result set
// increment your array counter and set current user id
$i++; // will set value to 0 on first iteration
$current_user_id = $row['user_id'];
// build new array entry
$results[$i] = new stdClass();
$results[$i]->user_id = $current_user_id;
$results[$i]->fields = array();
}
// build field object for insertion
$field = new stdClass();
$field->field_id = $row['field_id'];
$field->value = $row['value'];
$results[$i]->fields[] = $field;
}
On encoding $results this would give you a JSON structure like this:
[
{
"user_id":"461",
"fields": [
{
"field_id":"18",
"value":"foobar"
},
{
"field_id":"19",
"value":"abcxyz"
}
]
},
...
]
This data structure is going to be more readily usable by consuming app than some solution which requires exploding concatenated field id/value strings. Also note that I have not included id field anywhere in data structure, as it has no meaning in this context. If you truly needed that id, you could add it as another property in the field object since that is where there is a one-to-one relationship (not with user_id).
Based on your comment, if the field value is known and you need to access it via field_id index, you can slightly modify what I have shown above to build index-able field listing rather than a simply array of objects:
$results = array();
$i = -1;
$current_user_id = '';
while ($row = [YOUR MySQL FETCH MECHANISM HERE]) {
// determine if this record represents a new user id in the result set
// if so, we need to set up the user object and start another entry in top level array
if($current_user_id != $row['user_id']) {
// you have moved to a new user in the result set
// increment your array counter and set current user id
$i++; // will set value to 0 on first iteration
$current_user_id = $row['user_id'];
// build new array entry
$results[$i] = new stdClass();
$results[$i]->user_id = $current_user_id;
$results[$i]->fields = array();
}
// insert field value at field_id index position
$results[$i]->fields[$row['field_id']] = $row['value'];
}
This would give you a JSON representation like this.
[
{
"user_id":"461",
"fields": {
"18":"foobar",
"19":"abcxyz"
}
},
...
]
This would allow easy look-up by client based on field id. Of course you may want to consider similar for user_id. From the user object you could just access fields->18 (or similar based on on client language syntax).

How to add to an array in a database and get back each array and display it

How can I add a value into an array in a database row, and then later on, when I want to get values of the array, simply display each different array value on a new line?
Also, how do arrays work in mysql and how to get the value of it?
Filed testField has serialized data.
$arrayData = array('one','two','three');
$serializedData = serialize($arrayData);
Mysql insertion:
insert INTO table ('testField') Values ($serializedData);
To get data:
select testField from table where id=1
You are getting here some string value. Then you should unserialize this string to get array:
$arrayData = unserialize($selectResultValue);
Look here for more details about serialize function:
http://php.net/manual/en/function.unserialize.php
MySQL does not have a native array data type. So, your first step is to figure out how you will store the elements of the array in a MySQL table.
Will you store each array element in its own database row?
elem val
1 value1
2 value2
...
n valuen
Or will you store the arraw as a series of concatenated values in a single row, something like this?
values
value1,value2,value3,...,valuen
In the first case, you can update a single array element easily:
UPDATE array SET val=newValue
WHERE elem=updatedElement
In the second case, you'll have to read the values column, break it out (deserialize it) into an array, change the element or elements you want to change, then gather it up (serialize it) back into a values column, and update your mySQL table. #Anthony pointed this out.
You need to answer the question about how you're storing the array before you can start to figure out how you will update it.
save array
$foo = array(1,2,3);
mysql_query(sprintf("INSERT INTO some_table ('foo') VALUES ('%s')", serialize($foo));
foo will appear as a string 1,2,3 in the database now
fetch array
$result = mysql_query("SELECT id, foo FROM some_table")
$item = mysql_fetch_object($result);
$foo = $item->foo;
$foo = unserialize($foo);
add data to array
$foo[] = 4;
$foo = array_uniq($foo); // you might want to ensure only unique values
mysql_query(sprintf("UPDATE some_table SET foo='%s' WHERE id=%d", serialize($foo), $item->id);
foo will appear as a string 1,2,3,4 in the database now

An example of arrays being used in web development

I was talking to a person today who mentioned he used arrays when calling parameters or for other reasons when pulling data from the database etc.
Basically my question is: how would you use arrays in web development?
For example:
If you had a url like this (a social dating site)
http://www.example.com/page.php?sid=1&agefrom=30&ageto=40&sex=female&loccation=los angeles
How I would query the browse page (when showing a list of users) is
$id = mysql_real_escape_string($_GET['id']);
$agefrom = mysql_real_escape_string($_GET['agefrom']);
$ageto = mysql_real_escape_string($_GET['ageto']);
$sex = mysql_real_escape_string($_GET['sex']);
$location = mysql_real_escape_string($_GET['location']);
mysql_query("select from table where id = '$id' and agefrom='$agefrom' [.....the rest of the query]")
Can this be done with arrays? What if a location wasn't selected or the age wasn't entered? If i did the query it might fail.
I hope my question is more clear now.
Arrays make it easy to hold a set of values, or key => value pairs, inside a variable. It also makes it easy to iterate over a set of values.
foreach ($myarray as $key => $value)
{
// do something with this key and value
}
If you are passing a large number of values to a function, and this set of values could be thought of as a list or a lookup table, then you would use an array.
Please consult the PHP manual on arrays for more information.
Edit:
I think I see what you mean now. It can be helpful to sort of 'abstract' your database calls by creating a function that accepts values as an array. For example:
function editrecord($recordid, $values)
{
// SQL is generated by what is in $values, and then query is run
// remember to check keys for validity and escape values properly
}
That's an extreme simplication of course.
Arrays are an important feature of any language, they have O(1) (constant time) random access and can be used as a base data structure to make more complex types.
Specifically talking about PHP, the arrays are used VERY often, the language itself uses them for example to grab the GET and POST parameters.
To get data, you can also make use of arrays in PHP.
You can use mysql_fetch_assoc, this will retch a result row from the database as an associative array, each index of the array will represent a column of data of the current row:
//...
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
// Here, the $row variable is an associative array.
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}

Categories