I need to get the the distinct 'uid' and its corresponding 'name' , how can I do this in a multidimensional array?
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Jane Doe',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
),
array(
'uid' => '40489',
'name' => 'Jane Doe',
'pic_square' => 'urlof40489'
));
sample output:
$data = [{uid: '100', name: 'Sandra Shush'},{uid: '5465', name: ['Stefanie Mcmohn','Jane Doe']}, {uid: '40489', name: ['Michael','Jane Doe']}]
tried working with array_columns and array_keys but i cant think of the right way to get this.
Try Something like this , here i am storing uid to an array and checking is it already available in the array with in_array function
<?php
$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'
),
array(
'uid' => '40489',
'name' => 'Jane Doe',
'pic_square' => 'urlof40489'
));
$newUserDb = array();
$arrayUserId=array();
foreach ($userdb as $user) {
$newUserDbSingle=array();
$nameArray=array();
if (in_array($user['uid'], $arrayUserId))
{
$key = array_search ($user['uid'], $arrayUserId);
$nameArray=$newUserDb[$key]['name'];
array_push($newUserDb[$key]['name'], $user['name']);
}
else
{
unset($user['pic_square']);
$arrayUserId[]=$user['uid'];
$newUserDbSingle=$user;
$newUserDbSingle['name']=array($user['name']);
$newUserDb[]=$newUserDbSingle;
}
}
print_r($newUserDb);
?>
Try this solution:
$data = [];
foreach($userdb as $user)
{
if(array_key_exists($user['uid'], $data))
{
array_push($obj->name, $user['name']);
}
else
{
$obj = new stdClass;
$obj->uid = $user['uid'];
$obj->name = [];
array_push($obj->name, $user['name']);
$data[$user['uid']] = $obj;
}
}
print_r($data);
I have this function that does very close to what yo need, just modify the return as per your request. Good luck
function array_searchRecursive($needle, $haystack, $strict = false, $path = array()) {
if (!is_array($haystack)) {
return false;
}
foreach ($haystack as $key => $val) {
if (is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path)) {
$path = array_merge($path, array($key), $subPath);
return $path;
} elseif ((!$strict && $val == $needle) || ($strict && $val === $needle)) {
$path[] = $key;
return $path;
}
}
return false;
}
You can try the following approach:
$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'
),
array(
'uid' => '40489',
'name' => 'Jane Doe',
'pic_square' => 'urlof40489'
));
$nameArray = [];
$myUuid = '40489';
foreach ($userdb as $user) {
if ($myUuid == $user['uid']) {
array_push($nameArray, $user['name']);
}
}
print_r($nameArray);
and moreover, you can get any parameter or anything you required from the above array from that foreach loop.
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.
i have the following array:
$array[] = array('person'=>'1','name'=>'john','children'=>array(array('person'=>'11','name'=>'frank'),array('person'=>'12','name'=>'billie'),array('person'=>'13','name'=>'will')));
$array[] = array('person'=>'11','name'=>'frank','children'=>array(array('person'=>'111','name'=>'jack'),array('person'=>'112','name'=>'jamie')));
$array[] = array('person'=>'12','name'=>'billie','children'=>array(array('person'=>'121','name'=>'melanie'),array('person'=>'122','name'=>'fran'),array('person'=>'123','name'=>'monica')));
$array[] = array('person'=>'13','name'=>'will');
$array[] = array('person'=>'111','name'=>'jack');
$array[] = array('person'=>'112','name'=>'jamie');
$array[] = array('person'=>'121','name'=>'melanie');
$array[] = array('person'=>'122','name'=>'fran');
$array[] = array('person'=>'123','name'=>'monica','children'=>array(array('person'=>'1231','name'=>'marcus'),array('person'=>'1232','name'=>'fiona')));
$array[] = array('person'=>'1231','name'=>'marcus');
$array[] = array('person'=>'1232','name'=>'fiona');
I need it to be reduced to a simple key/value array, with "child=>parent", e.g.:
array('frank'=>'john');
array('billie'=>'john');
...
array('marcus'=>'monica');
I tried with recursive function but with no luck, this is quite a brainer to me:
function buildTree($inputArray, $nameToCheck){
$arrayFinal = array();
foreach($inputArray as $data){
if($data['name'] == $nameToCheck){
if (is_array($data['children'])){
foreach($data['children'] as $childrenName){
$name = $childrenName['name'];
$arrayFinal[$name] = buildTree($inputArray, $name);
}
}
}
}
return $arrayFinal;
}
any idea ?
Is this what you want? example
<?php
$array[] = array(
'person' => '1', 'name' => 'john',
'children' => array(
array('person' => '11', 'name' => 'frank'),
array('person' => '12', 'name' => 'billie'),
array('person' => '13', 'name' => 'will')
)
);
$array[] = array(
'person' => '11', 'name' => 'frank',
'children' => array(
array('person' => '111', 'name' => 'jack'),
array('person' => '112', 'name' => 'jamie')
)
);
$array[] = array(
'person' => '12', 'name' => 'billie',
'children' => array(
array('person' => '121', 'name' => 'melanie'),
array('person' => '122', 'name' => 'fran'),
array('person' => '123', 'name' => 'monica')
)
);
$array[] = array('person' => '13', 'name' => 'will');
$array[] = array('person' => '111', 'name' => 'jack');
$array[] = array('person' => '112', 'name' => 'jamie');
$array[] = array('person' => '121', 'name' => 'melanie');
$array[] = array('person' => '122', 'name' => 'fran');
$array[] = array(
'person' => '123', 'name' => 'monica',
'children' => array(
array('person' => '1231', 'name' => 'marcus'),
array('person' => '1232', 'name' => 'fiona')
)
);
$array[] = array('person' => '1231', 'name' => 'marcus');
$array[] = array('person' => '1232', 'name' => 'fiona');
$output = [];
foreach ($array as $parent) {
if (isset($parent["children"])) {
foreach ($parent["children"] as $child) {
$output[] = array($child["name"] => $parent["name"]);
}
}
}
print "<pre>";
print_r($output);
print "</pre>";
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.
I have two arrays with nearly the same structure.
The first array is $_POST data while the second one holds regex rules and some other stuff for data validation.
Example:
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
)
);
$structure = array(
'address' => array(
'city' => array(
'regex' => 'someregex'
)
)
);
Now I want to check
$data['address']['city'] with $structure['address']['city']['regex']
or
$data['foo']['bar']['baz']['xyz'] with $structure['foo']['bar']['baz']['xyz']['regex']
Any ideas how to achieve this with a PHP function?
Edit: It seems that I found a solution by myself.
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
),
'mail' => 'test#test.tld'
);
$structure = array(
'address' => array(
'city' => array(
'regex' => 'some_city_regex1',
)
),
'mail' => array(
'regex' => 'some_mail_regex1',
)
);
function getRegex($data, $structure)
{
$return = false;
foreach ($data as $key => $value) {
if (empty($structure[$key])) {
continue;
}
if (is_array($value) && is_array($structure[$key])) {
getRegex($value, $structure[$key]);
}
else {
if (! empty($structure[$key]['regex'])) {
echo sprintf('Key "%s" with value "%s" will be checked with regex "%s"', $key, $value, $structure[$key]['regex']) . '<br>';
}
}
}
return $return;
}
getRegex($data, $structure);
Given these arrays:
$data = array(
'name' => 'John Doe',
'address' => array(
'city' => 'Somewhere far beyond'
),
'foo' => array(
'bar' => array(
'baz' => array(
'xyz' => 'hij'
)
)
)
);
$structure = array(
'address' => array(
'city' => array(
'regex' => '[a-Z]'
)
),
'foo' => array(
'bar' => array(
'baz' => array(
'xyz' => array(
'regex' => '[0-9]+'
)
)
)
)
);
and this function:
function validate ($data, $structure, &$validated) {
if (is_array($data)) {
foreach ($data as $key => &$value) {
if (
array_key_exists($key, $structure)
and is_array($structure[$key])
) {
if (array_key_exists('regex', $structure[$key])) {
if (!preg_match($structure[$key]['regex'])) {
$validated = false;
}
}
validate($value, $structure[$key], $validated);
}
}
}
}
you can check the arrays against each other and get a validation result like so:
$validated = true;
validate($data, $structure, $validated);
if ($validated) {
echo 'everything validates!';
}
else {
echo 'validation error';
}
Ah, you've found a solution. Very nice.
Let's say i have an array like this:
$array = array(
0 =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
1=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
21 =>
array(
'value' => 'adresa#gmail.com' ,
'name' => 'name1`' ),
23 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
24 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
26 =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
27 =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);
I want to know if exists duplicated value in array with key 'value' I know how to do this if i want a specified value but general no. The result must be an array with no duplicated values(eg:
$array = array(
0 =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
1=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
23 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
26 =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
27 =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);`
Please help me.
This is my try
function has_dupes($array){
$dupe_array = array();
foreach($array as $val){
if(++$dupe_array[$val] > 1){
return true;
}
}
return false;
}
Try this way:
$array = array(
'0' =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
'1'=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
'21' =>
array(
'value' => 'adresa#gmail.com' ,
'name' => 'name1`' ),
'23' =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
'24' =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
'26' =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
'27' =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);
$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
$result = array_unique($array);
print_r($result);
And if you want to store all unique data in one array do it like this:
//declare $array
$unique_array = array();
foreach ($array as $key => $type) {
foreach($type as $vale => $name) {
if ($vale == 'value') {
//echo $name . '<br>';
array_push($unique_array, $name);
}
}
}
$result = array_unique($unique_array);
foreach ($result as $res) {
echo $res . '<br>';
}
Try this
$values = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($values as $key => $value)
{
if ( is_array($value) )
{
$values[$key] = $value;
}
}
print_r($values);
$unique_data = array(); // the result array
$duplicate_data = array();
$seen = array();
foreach ($array as $key => $arr) {
$value = $arr['value'];
if (!isset($seen[$value])) {
$seen[$value] = '';
$unique_data[$key] = $arr;
} else {
$duplicate_data[$key] = $arr; // optional
}
}
unset($seen); // optional in function scope