Array:
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'abc.jpg'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'Michael.jpg'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'xyz.jpg'
)
);
Search value:
Michael
Expected output:
$userdb = array(
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'Michael.jpg'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'xyz.jpg'
)
);
As you can check what I want can anyone please tell me How can I achieve this result by using PHP. I don't care whether my search term is in 'uid', 'name', or 'pic_square' key but I want to get array whenever my search term result is matching. Is there any inbuilt function which can achieve this result?
Another way is to use array_filter() to remove elements that not match to your search.
$userdb = array(
array('uid' => '100', 'name' => 'Sandra Shush', 'pic_square' => 'abc.jpg'),
array('uid' => '5465', 'name' => 'Stefanie Mcmohn', 'pic_square' => 'Michael.jpg'),
array('uid' => '40489', 'name' => 'Michael', 'pic_square' => 'xyz.jpg')
);
$search = 'Michael';
$out = array_filter($userdb, function($item) use($search) {
return $item['name'] == $search || strpos($item['pic_square'], $search) !== false;
});
print_r($out);
Output:
Array (
[1] => Array (
[uid] => 5465
[name] => Stefanie Mcmohn
[pic_square] => Michael.jpg
)
[2] => Array (
[uid] => 40489
[name] => Michael
[pic_square] => xyz.jpg
)
)
Very simple solution is to apply simple foreach() with strpos()
1.iterate over the array using foreach()
2.Check that search value exist in any one of three id, name,pic_square or not? if yes then add that whole sub-array to a new array.
3.This new array is your desired result.
$search_value = 'Michael';
$final_array = [];
foreach($userdb as $userd){
if(strpos($userd['uid'],$search_value)!== false || strpos($userd['name'],$search_value)!== false || strpos($userd['pic_square'],$search_value)!== false){
$final_array[] = $userd;
}
}
print_r($final_array);
Output:- https://eval.in/997896
You can use preg_grep to match the search in a loose comparison.
$search = "Michael";
Foreach($userdb as $key => $arr){
If(preg_grep("/" . $search ."/", $arr)){
$res[] = $userdb[$key];
}
}
Var_dump($res);
I loop through the array and if a match is made with preg_grep it's added to the result array.
https://3v4l.org/BPJBC
Preg_grep will search the full array and not only items hardcoded.
This can be both a good and a bad thing obviously.
As an example if your DB expands with 'alias' key preg_grep will search that to without needing to change the code.
See here for an example:
https://3v4l.org/lOao3
This should do the trick.
foreach($userdb as $i=>$r){
foreach($r as $j=>$v){
#if($v matches the querystring)
#return $r / append $r to a match list
}
}
But NOTE THAT since there are no indexing and all, this will run in O(N^2) which is the worst case...
EDIT
After some research, came up with the following solution.
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'abc.jpg'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'Michael.jpg'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'xyz.jpg'
)
);
$search = "Michael";
$out = array_filter($userdb, function($item) use($search) {
foreach($item as $k=>$v){
if(preg_match("/$search/", $v) == 1){
return true;
}
}
});
echo json_encode($out);
The solution employs array_filter function (Syscall's answer is acknowledged hereby, that was the pointer for me to research on array_filter further) to reduce the array using a filter, where the filter being a preg_match executed on each attribute of the associative array elements. If a match found, it returns true, which will add the matching element into $out.
Related
$userarray = array(
array(
'uid' => '100',
'extraid' => 2,
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'extraid' => 2,
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'extraid' => 2,
'name' => 'Michael',
'pic_square' => 'urlof40489'
),
array(
'uid' => '512',
'extraid' => 3,
'name' => 'Hillary',
'pic_square' => 'urlof409'
),
array(
'uid' => '792',
'extraid' => 3,
'name' => 'James',
'pic_square' => 'urlof489'
),
);
$all_category = $this->common->getAll(TABLE_CONF_CATEGORIES, 'year', $year);
foreach($all_category as $cats) {
$key = array_search($cats->id, array_column($userarray , 'extraid'));echo $key;
if($key) {
$userarray[$key]->category_name = $cats->category_name;
}
}
In this array, I need to get every first element of extraid. i.e. if extraid = 2, here's 3 elements are there, so I need to get the first array. If extraid = 3, then there's 2 arrays are there, & I need the first array to fetched, & so on.
this all_category is another array where the corresponding extraid values are present, so looped it, & did an array search to find the value.
<?php
$userarray = [
[
'uid' => '100',
'extraid' => 2,
'name' => 'Sandra Shush',
'pic_square' => 'urlof100',
],
[
'uid' => '5465',
'extraid' => 2,
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100',
],
[
'uid' => '40489',
'extraid' => 2,
'name' => 'Michael',
'pic_square' => 'urlof40489',
],
[
'uid' => '512',
'extraid' => 3,
'name' => 'Hillary',
'pic_square' => 'urlof409',
],
[
'uid' => '792',
'extraid' => 3,
'name' => 'James',
'pic_square' => 'urlof489',
],
];
// final output array
$all_category = [];
// list of already set ids
$ids = [];
foreach($userarray as $user) {
if( !isset($ids[$user['extraid']]) ){
$ids[$user['extraid']] = true;
$all_category[]= $user;
}
}
print_r($all_category);
Loop through your array
Check if the extraid is already in your array
If it is then move to the next array element
If it is not, then add it to your final output array, and store the id in our list of ids we've already seen.
Solution for the case that several fields should be unique. Unique here means that the content of all fields must match. The input array itself is reduced.
$fieldNames = ['extraid'];
$filterCols = [];
$flipFields = array_flip($fieldNames);
foreach($userarray as $key => $row){
$fieldsFromRow = array_intersect_key($row,$flipFields);
if(in_array($fieldsFromRow, $filterCols)) {
unset($userarray[$key]);
}
else {
$filterCols[] = $fieldsFromRow;
}
}
$userarray = array_values($userarray);
The code comes from the TableArray class. With this class the solution looks like this:
$all_category = TableArray::create($userarray)
->filterUnique(['extraid'])
->fetchAll()
;
When using the class, the input array is retained.
This question already has answers here:
Elegant way to search an PHP array using a user-defined function
(7 answers)
Closed 3 years ago.
Assume we have the following 2-dimensional array:
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
If I want to search a key I can use (and get 0 in this example):
$key = array_search('100', array_column($userdb, 'uid'));
But what do I use if I want to get the key for two attributes that should match a specific value. Like I want to search for the key that has uid = '100' AND name = 'Sandra Shush' ?
It's probably simplest just to use a foreach over the values e.g. this function will return a similar value to array_search:
function find_user($userdb, $attributes) {
foreach ($userdb as $key => $user) {
if (empty(array_diff($attributes, $user))) return $key;
}
return false;
}
echo find_user($userdb, array('name' => 'Stefanie Mcmohn', 'uid' => 5465));
Output
1
Demo on 3v4l.org
why not loop over the array?
$foundKey = false;
foreach($userdb as $key => $user){
if($user['uid']=='100' && $user['name '] == 'Sandra Shush'){
$foundKey = $key;
}
}
How do I merge two multi-dimensional arrays using different keys that have matching values?
i.e. I want the data in arrayOne, 'Member'=> '45', to merge with the data in arrayTwo, 'id' => '45'.
I don't have access to the query, just the result array.
First Array:
arrayOne
array (
558 =>
array (
'id' => '558',
'Member' => '45',
'Status' => 'Active',
),
559 =>
array (
'id' => '559',
'Member' => '46',
'Status' => 'Active',
),
)
Second Array:
arrayTwo
array (
45 =>
array (
'id' => '45',
'Name' => 'Johnson',
),
46 =>
array (
'id' => '46',
'Name' => 'Smith',
),
)
Desired Array would be something like this:
arrayThree
array (
45 =>
array (
'id' => '45',
'Name' => 'Johnson',
'Member' => '45',
'Status' => 'Active',
),
46 =>
array (
'id' => '46',
'Name' => 'Smith',
'Member' => '46',
'Status' => 'Active',
),
)
This is the code I've most recently tried, which does merge the records, but it doesn't merge them by their matching values. Thank-you for any help!
function my_array_merge($arrayOne, $arrayTwo) {
$result = arrayThree();
foreach($arrayOne as $key => $value) {
$result[$key] = array_merge($value, $arrayTwo[$key]);
}
return $result;
}
echo "<pre>";
print_r($result);
echo "</pre>";
You can use array_map:
$array1 = array_combine(array_column($array1, 'Member'), $array1);
$result = array_map(function ($item2) use ($array1) {
$item1 = isset($array1[$item2['id']]) ? $array1[$item2['id']] : null;
if ($item2) {
$item2['Member'] = $item1['Member'];
$item2['Status'] = $item1['Status'];
}
return $item2;
}, $array2);
Here is working demo.
Yesterday I ask here Append array values to another array by keys comparison and I have tried a few things without success. I have two arrays $result and $result1. count($result) is 204640 and count($result1) is 129849 so they are huge. The arrays is the result of a PDO statement execution as shown in code below. This is an example for $result array:
'00180000015oGSWAA2' =>
array (
'accountId' => '00180000015oGSWAA2',
'npi' => '1053576223',
'firstname' => 'Jack',
'lastname' => 'Cheng',
'title' => '',
'accountLastModifiedDate' => '2014-09-09 17:37:15',
'suffix' => '',
'fax' => '',
'address1' => '853 N CHURCH ST',
'city' => 'SPARTANBURG',
'stateLicensedId' => '31191',
'state' => 'SC',
'phone' => '',
'zip' => '29303',
'address2' => '',
'addressLastModifiedDate' => '2014-09-04 08:44:17',
),
'00180000015oGeXAAU' =>
array (
'accountId' => '00180000015oGeXAAU',
'npi' => '1629067301',
'firstname' => 'Fred',
'lastname' => 'Thaler',
'title' => '',
'accountLastModifiedDate' => '2014-09-09 17:36:41',
'suffix' => '',
'fax' => '',
'address1' => '1 PEARL ST',
'city' => 'BROCKTON',
'stateLicensedId' => '58249',
'state' => 'MA',
'phone' => '',
'zip' => '2301',
'address2' => '',
'addressLastModifiedDate' => '2014-09-04 04:25:44',
)
And this is an example for $result1 array:
'001S000000nBvryIAC' =>
array (
'tid' => '04T800000008zySEAQ',
'acsLastModifiedDate' => '2015-01-06 17:19:48',
),
'00180000015oGeXAAU' =>
array (
'tid' => '04T800000008zzgEAA',
'acsLastModifiedDate' => '2015-01-07 04:06:40',
),
'001S000000nYWcYIAW' =>
array (
'tid' => '04T800000008zySEAQ',
'acsLastModifiedDate' => '2015-02-25 15:45:01',
),
As you can see $result[1] and $result1[1] shares the same keys, right? Ok, then what I need is to push the content of $result1[1] on the end of $result[1] and getting something like:
'00180000015oGeXAAU' =>
array (
'accountId' => '00180000015oGeXAAU',
'npi' => '1629067301',
'firstname' => 'Fred',
'lastname' => 'Thaler',
'title' => '',
'accountLastModifiedDate' => '2014-09-09 17:36:41',
'suffix' => '',
'fax' => '',
'address1' => '1 PEARL ST',
'city' => 'BROCKTON',
'stateLicensedId' => '58249',
'state' => 'MA',
'phone' => '',
'zip' => '2301',
'address2' => '',
'addressLastModifiedDate' => '2014-09-04 04:25:44',
'tid' => '04T800000008zzgEAA',
'acsLastModifiedDate' => '2015-01-07 04:06:40',
)
Meaning when keys are equal in both arrays then merge or append values from the second one into the first one. Right now my best approach is the following:
// PDO statement
$result = $stmt->fetchAll();
// PDO statement
$result1 = $stmt->fetchAll();
foreach ($result as $key => $row) {
foreach ($result1 as $key1 => $row1) {
if ($key === $key1) {
array_push($row, array_shift($row1));
}
}
}
var_dump($row);
But it takes an eternity due to arrays length, so any advice in how to speedup this?
UPDATE: almost a solution
Based on #decese solution I have rewrite this a bit so my apologies in first and take a look to this. Now I called arrays as $oneArr and $twoArr and also I write a small output examples (don't kill me just yet):
// var_export($oneArr)
'00180000015oGSWAA2' =>
array (
'target_id' => '00180000015oGSWAA2',
'firstname' => 'Jack',
),
'00180000015oGeXAAU' =>
array (
'target_id' => '00180000015oGeXAAU',
'firstname' => 'Fred',
)
// var_export($twoArr)
'001S000000nBvryIAC' =>
array (
'tid' => '04T800000008zySEAQ',
'acsLastModifiedDate' => '2015-01-06 17:19:48',
),
'00180000015oGeXAAU' =>
array (
'tid' => '04T800000008zzgEAA',
'acsLastModifiedDate' => '2015-01-07 04:06:40',
)
This is the ouput I want to achieve, meaning when keys are equal in both arrays then merge or append values from the second one into the first one:
'00180000015oGeXAAU' =>
array (
'target_id' => '00180000015oGeXAAU',
'firstname' => 'Fred',
'tid' => '04T800000008zzgEAA',
'acsLastModifiedDate' => '2015-01-07 04:06:40',
)
I have this done, again based on first answer which I thanks a lot for clear a bit things to me, with the following code:
// Fetch results from first SQL query
$result = $stmt->fetchAll();
// Fetch only two keys from the entire and put them on $oneArr
foreach ($result as $row) {
$oneArr[$row['target_id']] = [
'target_id' => $row['target_id'],
'firstname' => $row['firstname']
];
}
// Fetch results from second SQL query
// yes, var names are the same not matter, I will only use one time
$result = $stmt->fetchAll();
// Fetch only two keys from the entire and put them on $twoArr
foreach ($result as $row) {
$twoArr[$row['target_id']] = [
'tid' => $row['tid'],
'acslmd' => $row['acslmd']
];
}
$i = 0;
foreach ($oneArr as $keyOneArr => $valueOneArr) {
if (array_key_exists($keyOneArr, $twoArr)) {
array_push($oneArr[$keyOneArr], $twoArr[$keyOneArr]);
$i++;
}
}
var_export($oneArr);
But result is not the same as I want since I got this:
'00180000015oGeXAAU' =>
array (
'target_id' => '00180000015oGeXAAU',
'firstname' => 'Fred',
0 =>
array (
'tid' => '04T800000008zzgEAA',
'acslmd' => '2015-01-07 04:06:40',
),
),
How I can avoid the extra array on the result array?
PS: Times looks good now: Call time was 00:01:34
Looks like your arrays are actually indexed by the ids, so do this:
foreach ($result1 as $key => $value) {
if (isset($result[$key])) {
$result[$key] += $value;
}
}
Of course, doing all this work in the database using a JOIN would make the most sense to begin with, if possible.
You could use array_merge_recursive
See my working example: http://3v4l.org/hQERW
Note: in the provided data, only 00180000015oGeXAAU is common to both arrays, so it only merges the values for that key
Basically, just call
$result = array_merge_recursive($result, $result1);
PHP.net says:
array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.
I have the following array of associative arrays.
$result = array(
(int) 0 => array(
'name' => 'Luke',
'id_number' => '1111',
'address' => '1544addr',
'time_here' => '2014-04-12 13:07:08'
),
(int) 1 => array(
'name' => 'Sam',
'id_number' => '2222',
'address' => '1584addr',
'time_here' => '2014-04-12 14:15:26'
I want to remove selected elements from this array such that it will look like this;
array(
(int) 0 => array(
'name' => 'Luke',
'id_number' => '1111'
),
(int) 1 => array(
'name' => 'Sam',
'id_number' => '2222',
This is the code I wrote;
foreach($result as $value)
{
unset($value('address') );
unset($value('time_here') );
}
When I run the code, Apache web server crashed.
Can the smarter members point out what did I do wrong? Thank you very much.
Array notation is wrong, use this;
$finalResult = array();
foreach($result as $value)
{
unset($value['address'] );
unset($value['time_here'] );
$finalResult[] = $value;
}
Here is a working demo: Demo
That is because you are not accessing array correctly. Use square bracket insted of round brackets :
foreach($result as $value)
{
unset($value['address'] );
unset($value['time_here'] );
}