refactor multidimensional json in php by keys - php

I'm working on project and I'm trying to refactor a json object By array of $keys
for example:
as input:
{
"message": "User Detail",
"code": 200,
"error": false,
"results": {
"user": {
"id": 2,
"name": "ali",
"country": {
"id": 50,
"name": "EGY"
}
},
"access_token": "=PQLkHJYIXB2uKbCq4sXIjD2GpBU2o"
}
}
as input: array of $keys
$kyes = [
'code',
'user'=>[
'id',
'country'=>['name']
]
]
expect to return:
{
"code": 200,
"user": {
"id": 2,
"country": {
"name": "egy",
}
}
}
code I have tried:
public function filter_multidimensional(array $array, array $keys){
$val = [];
foreach ($array as $key => $value) {
if (in_array($key,$keys)){
$val[$key] = $value;
}elseif (is_array($value)) {
$val[$key] = $this->filter_multidimensional($keys,$value);
}
}
return $val;
}
//-------
$this->filter_multidimensional($json,['code','user'=>['id','country'=>['name']]])
Unfortunately output:
update 1
the json input is not const, so my code must be adapt. and that's I'm trying to do.

Thanks for #404-not-found his code was amazing but missing a small thing
which is in this code
if (is_array($key)) {
$val[$objectKey] = filter_multidimensional($array, $key);
}
you still give the find function the base array which will return the first value it will find in the case of ['user'=>['id',"country"=>['id']]] and the solution for this will be passing the parent array of the object key
So the full code will be
<?php
function filter_multidimensional(array $array, array $keys) {
if (empty($keys) || empty($array)) {
return [];
}
$val = [];
// In the structure of $keys, both key and value are technically "keys".
// In the example `['code','user'=>['id']]`, 'code' and 'id' are both array *values*,
// while 'user' is a key.
//
// So, $objectKey is a search key which contains sub-keys, while $key is just a regular string.
foreach ($keys as $objectKey => $key) {
// If $key is an array, then recursively search, and save the results to the $objectKey string.
if (is_array($key)) {
$val[$objectKey] = filter_multidimensional(findTill($array,$objectKey), $key);
}
// If the desired key exists, then save the value.
else if (array_key_exists($key, $array)) {
$val[$key] = $array[$key];
}
// Otherwise, $key is a string, but it does not exist at this level of $array,
// so search the next-level up in $array, and merge the results into this level of $val.
else {
$val = array_merge($val, filter_multidimensional(nextLevel($array), [$key]));
}
}
return $val;
}
function findTill($array,$key) {
if (array_key_exists($key, $array)) {
return $array[$key];
}
return findTill(nextLevel($array),$key);
}
/**
* Create an array that contains only the array values from $array.
*
* Eg: If given ['a' => '1', 'b' => ['foo' => '2'], 'c' => ['hello' => 'world']],
* then return ['foo' => '2', 'hello' => 'world']
*
* #param array $array
* #return array
*/
function nextLevel(array $array) {
// Merge all of the array values together into one array
return array_reduce(
// Strip the keys
array_values(
// Filter to return only keys where the value is an array
array_filter(
$array,
function ($value) {
return is_array($value);
}
)
),
'array_merge',
[]
);
}
//-------
$obj = [
"message" => "User Detail",
"code" => 200,
"error" => false,
"results" => [
"user" => [
"id" => 2,
"name" => "ali",
"country" => [
"id" => 50,
"name" => "EGY",
],
],
"access_token" => "=PQLkHJYIXB2uKbCq4sXIjD2GpBU2o",
],
];
$result = filter_multidimensional($obj,['code','user'=>['id','country'=>['id','name']],"access_token"]);

I believe this method works. I flipped your logic, and instead of searching the $array to see if it's keys match any of those in $keys, I instead recursively searched $keys to see if $array had any matching values.
function filter_multidimensional(array $array, array $keys) {
if (empty($keys) || empty($array)) {
return [];
}
$val = [];
// In the structure of $keys, both key and value are technically "keys".
// In the example `['code','user'=>['id']]`, 'code' and 'id' are both array *values*,
// while 'user' is a key.
//
// So, $objectKey is a search key which contains sub-keys, while $key is just a regular string.
foreach ($keys as $objectKey => $key) {
// If $key is an array, then recursively search, and save the results to the $objectKey string.
if (is_array($key)) {
$val[$objectKey] = filter_multidimensional($array, $key);
}
// If the desired key exists, then save the value.
else if (array_key_exists($key, $array)) {
$val[$key] = $array[$key];
}
// Otherwise, $key is a string, but it does not exist at this level of $array,
// so search the next-level up in $array, and merge the results into this level of $val.
else {
$val = array_merge($val, filter_multidimensional(nextLevel($array), [$key]));
}
}
return $val;
}
/**
* Create an array that contains only the array values from $array.
*
* Eg: If given ['a' => '1', 'b' => ['foo' => '2'], 'c' => ['hello' => 'world']],
* then return ['foo' => '2', 'hello' => 'world']
*
* #param array $array
* #return array
*/
function nextLevel(array $array) {
// Merge all of the array values together into one array
return array_reduce(
// Strip the keys
array_values(
// Filter to return only keys where the value is an array
array_filter(
$array,
function ($value) {
return is_array($value);
}
)
),
'array_merge',
[]
);
}
//-------
$result = filter_multidimensional($obj,['code','user'=>['id','country'=>['name']]]);

You could use a combination of data_get and data_set to get what you want.
Change the input a bit so it's more consistent. Dot notation would be easiest.
$array = [
"message" => "User Detail",
"code" => 200,
"error" => false,
"results" => [
"user" => [
"id" => 2,
"name" => "ali",
"country" => [
"id" => 50,
"name" => "EGY",
],
],
"access_token" => "=PQLkHJYIXB2uKbCq4sXIjD2GpBU2o",
],
];
$keys = [
'code' => 'code',
'user.id' => 'results.user.id',
'user.country.name' => 'results.user.country.name',
];
$results = [];
foreach ($keys as $set_position => $get_position) {
data_set($results, $set_position, data_get($array, $get_position));
}

Related

search value in multi array [duplicate]

I have an array where I want to search the uid and get the key of the array.
Examples
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'
)
);
The function call search_by_uid(100) (uid of first user) should return 0.
The function call search_by_uid(40489) should return 2.
I tried making loops, but I want a faster executing code.
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchForId('100', $userdb);
It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.
Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.
If you want just one result:
$key = array_search(40489, array_column($userdb, 'uid'));
For multiple results
$keys = array_keys(array_column($userdb, 'uid'), 40489);
In case you have an associative array as pointed in the comments you could make it with:
$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!
Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!
In later versions of PHP (>= 5.5.0) you can use this one-liner:
$key = array_search('100', array_column($userdb, 'uid'));
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Usage: $results = searcharray('searchvalue', searchkey, $array);
Looks array_filter will be suitable solution for this...
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
PHP Code
<?php
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH); // With latest PHP third parameter is optional.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$values= print_r(array_values($found));
$keys = print_r(array_keys($found));
I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.
Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
/**
* #param array multidimensional
* #param string value to search for, ie a specific field name like name_first
* #param string associative key to find it in, ie field_name
*
* #return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).
/**
* #param array multidimensional
* #param string $search_value The value to search for, ie a specific 'Taylor'
* #param string $key_to_search The associative key to find it in, ie first_name
* #param string $other_matching_key The associative key to find in the matches for employed
* #param string $other_matching_value The value to find in that matching associative key, ie true
*
* #return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Use of function
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Result
Array ( [0] => 2 )
You can do that with combination of two functions, array_search & array_column.
$search_value = '5465';
$search_key = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));
print_r($userdb[$user]);
5465 is the user ID you want to search, uid is the key that contains user ID and $userdb is the array that is defined in the question.
References:
array_search on php.net
array_column on php.net
I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:
$arr = array(
'XXX'=>array(
'YYY'=> array(
'AAA'=> array(
'keyN' =>'value1'
)
),
'ZZZ'=> array(
'BBB'=> array(
'keyN' => 'value2'
)
)
//.....
)
);
$result = searchItemsByKey($arr,'keyN');
print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
[0] => value1
[1] => value2
)
Function code:
function searchItemsByKey($array, $key)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key)
$results[] = $array[$key];
foreach ($array as $sub_array)
$results = array_merge($results, searchItemsByKey($sub_array, $key));
}
return $results;
}
Here is one liner for the same,
$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];
Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if ($val[$sKey] == $id) {
return $key;
}
}
return false;
}
Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.
// Array Data Of Users
$userdb = array (
array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);
// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
echo "Search Result can not be found";
}
PHP Fiddle Example
I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not
$arr = array(
array(
'title' => 'abc'
)
);
Then i can use this
$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
echo 'exists';
} else {
echo 'notExists';
}
I think This is the Most simple way to define
I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:
function search_in_array_r($needle, $array) {
$found = array();
foreach ($array as $key => $val) {
if ($val[1] == $needle) {
array_push($found, $val[1]);
}
}
if (count($found) != 0)
return $found;
else
return null;
}
/**
* searches a simple as well as multi dimension array
* #param type $needle
* #param type $haystack
* #return boolean
*/
public static function in_array_multi($needle, $haystack){
$needle = trim($needle);
if(!is_array($haystack))
return False;
foreach($haystack as $key=>$value){
if(is_array($value)){
if(self::in_array_multi($needle, $value))
return True;
else
self::in_array_multi($needle, $value);
}
else
if(trim($value) === trim($needle)){//visibility fix//
error_log("$value === $needle setting visibility to 1 hidden");
return True;
}
}
return False;
}
you can use this function ;
https://github.com/serhatozles/ArrayAdvancedSearch
<?php
include('ArraySearch.php');
$query = "a='Example World' and b>='2'";
$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);
$Result = ArraySearch($Array,$query,1);
echo '<pre>';
print_r($Result);
echo '</pre>';
// Output:
// Array
// (
// [0] => Array
// (
// [a] => Example World
// [b] => 2
// )
//
// )
$a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];
$found = null;
$search = 'eee';
array_walk($a, function ($k, $v) use ($search, &$found) {
if (in_array($search, $k)) {
$found = $v;
}
});
var_dump($found);
Try this
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
?>
Just share, maybe can like this.
if( ! function_exists('arraySearchMulti')){
function arraySearchMulti($search,$key,$array,$returnKey=false)
{
foreach ($array as $k => $val) {
if (isset($val[$key])) {
if ((string)$val[$key] == (string)$search) {
return ($returnKey ? $k : $val);
}
}else{
return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);
}
}
return null;
}}
No one else has used array_reduce yet, so thought I'd add this approach...
$find_by_uid = '100';
$is_in_array = array_reduce($userdb, function($carry, $user) use ($find_by_uid){
return $carry ? $carry : $user['uid'] === $find_by_uid;
});
// Returns true
Gives you more fine control over the 'search' logic than array_search().
Note that I have used strict equality here but you could opt for different comparison logic. The $carry means the comparison needs to be true once, and the final result will be TRUE.
I was looking for functionality similar to that of MySQL LIKE %term%. Based on the answers on this page. I am able to search the JSON array from a file.
user_list.json looks as sample below:
{
"user-23456": {
"name": "John Doe",
"age": "20",
"email": "doe#sample.com",
"user_id": "23456"
},
"user-09876": {
"name": "Ronojoy Adams",
"age": "35",
"email": "joy#sample.com",
"user_id": "09876"
},
"user-34890": {
"name": "Will Artkin",
"age": "16",
"email": "will#sample.com",
"user_id": "34890"
},
}
/*
*search_key_like
*/
function search_key_like($value, $key, $array) {
$results=array();
$keyword = preg_quote($value, '~');
foreach ($array as $k => $val) {
//if name a is spell John and keyword is sent as joh or JOH it will return null
//to fix the issue convert the string into lowercase and uppercase
$data=array($val[$key],strtolower($val[$key]),strtoupper($val[$key]));
if (preg_grep('~' . $keyword . '~', $data)) {
array_push($results,$val[$key]);
}
}
return $results;
}
Usage===pulling the JSON file===
$user_list_json='./user_list.json';
if(file_exists($user_list_json) && file_get_contents($user_list_json)){
$file_json_data=file_get_contents($user_list_json);
$json_array_data=json_decode($file_json_data,true);
$user_name_like = search_key_like('ron', 'name', $json_array_data);
print "<pre>".print_r($user_name_like,true);
}
for( $i =0; $i < sizeof($allUsers); $i++)
{
$NEEDLE1='firstname';
$NEEDLE2='emailAddress';
$sterm='Tofind';
if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
{
$Fname= $allUsers[$i][$NEEDLE1];
$Lname= $allUsers[$i][$NEEDLE2];
$pos1 = stripos($Fname, $sterm);
$pos2=stripos($Lname, $sterm);//not case sensitive
if($pos1 !== false ||$pos2 !== false)
{$resultsMatched[] =$allUsers[$i];}
else
{ continue;}
}
}
Print_r($resultsMatched); //will give array for matched values even partially matched
With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.
Expanding on the function #mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
return $key;
}
}
return false;
}
For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"
If question i.e.
$a = [
[
"_id" => "5a96933414d48831a41901f2",
"discount_amount" => 3.29,
"discount_id" => "5a92656a14d488570c2c44a2",
],
[
"_id" => "5a9790fd14d48879cf16a9e8",
"discount_amount" => 4.53,
"discount_id" => "5a9265b914d488548513b122",
],
[
"_id" => "5a98083614d488191304b6c3",
"discount_amount" => 15.24,
"discount_id" => "5a92806a14d48858ff5c2ec3",
],
[
"_id" => "5a982a4914d48824721eafe3",
"discount_amount" => 45.74,
"discount_id" => "5a928ce414d488609e73b443",
],
[
"_id" => "5a982a4914d48824721eafe55",
"discount_amount" => 10.26,
"discount_id" => "5a928ce414d488609e73b443",
],
];
Ans:
function searchForId($id, $array) {
$did=0;
$dia=0;
foreach ($array as $key => $val) {
if ($val['discount_id'] === $id) {
$dia +=$val['discount_amount'];
$did++;
}
}
if($dia != '') {
echo $dia;
var_dump($did);
}
return null;
};
print_r(searchForId('5a928ce414d488609e73b443',$a));
Here is a better solution, in case your pulling data from a database or a multidimensional array
Example of a multidimensional array:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
function search_user_by_name($name, $array) {
foreach ($array as $keys) {
foreach ($keys as $key => $_user_record) {
if ($_user_record == $name) {
return [$key => $_user_record];//Return and array of user
}
}
}
return null;
}
Call the function:
$results = search_user_by_name('John', $records);
print_r($results);
Output: Array ( [first_name] => John )

Trying to loop through this nested array PHP [duplicate]

I have an array where I want to search the uid and get the key of the array.
Examples
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'
)
);
The function call search_by_uid(100) (uid of first user) should return 0.
The function call search_by_uid(40489) should return 2.
I tried making loops, but I want a faster executing code.
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchForId('100', $userdb);
It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.
Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.
If you want just one result:
$key = array_search(40489, array_column($userdb, 'uid'));
For multiple results
$keys = array_keys(array_column($userdb, 'uid'), 40489);
In case you have an associative array as pointed in the comments you could make it with:
$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!
Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!
In later versions of PHP (>= 5.5.0) you can use this one-liner:
$key = array_search('100', array_column($userdb, 'uid'));
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Usage: $results = searcharray('searchvalue', searchkey, $array);
Looks array_filter will be suitable solution for this...
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
PHP Code
<?php
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH); // With latest PHP third parameter is optional.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$values= print_r(array_values($found));
$keys = print_r(array_keys($found));
I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.
Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
/**
* #param array multidimensional
* #param string value to search for, ie a specific field name like name_first
* #param string associative key to find it in, ie field_name
*
* #return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).
/**
* #param array multidimensional
* #param string $search_value The value to search for, ie a specific 'Taylor'
* #param string $key_to_search The associative key to find it in, ie first_name
* #param string $other_matching_key The associative key to find in the matches for employed
* #param string $other_matching_value The value to find in that matching associative key, ie true
*
* #return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Use of function
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Result
Array ( [0] => 2 )
You can do that with combination of two functions, array_search & array_column.
$search_value = '5465';
$search_key = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));
print_r($userdb[$user]);
5465 is the user ID you want to search, uid is the key that contains user ID and $userdb is the array that is defined in the question.
References:
array_search on php.net
array_column on php.net
I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:
$arr = array(
'XXX'=>array(
'YYY'=> array(
'AAA'=> array(
'keyN' =>'value1'
)
),
'ZZZ'=> array(
'BBB'=> array(
'keyN' => 'value2'
)
)
//.....
)
);
$result = searchItemsByKey($arr,'keyN');
print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
[0] => value1
[1] => value2
)
Function code:
function searchItemsByKey($array, $key)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key)
$results[] = $array[$key];
foreach ($array as $sub_array)
$results = array_merge($results, searchItemsByKey($sub_array, $key));
}
return $results;
}
Here is one liner for the same,
$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];
Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if ($val[$sKey] == $id) {
return $key;
}
}
return false;
}
Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.
// Array Data Of Users
$userdb = array (
array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);
// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
echo "Search Result can not be found";
}
PHP Fiddle Example
I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not
$arr = array(
array(
'title' => 'abc'
)
);
Then i can use this
$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
echo 'exists';
} else {
echo 'notExists';
}
I think This is the Most simple way to define
I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:
function search_in_array_r($needle, $array) {
$found = array();
foreach ($array as $key => $val) {
if ($val[1] == $needle) {
array_push($found, $val[1]);
}
}
if (count($found) != 0)
return $found;
else
return null;
}
/**
* searches a simple as well as multi dimension array
* #param type $needle
* #param type $haystack
* #return boolean
*/
public static function in_array_multi($needle, $haystack){
$needle = trim($needle);
if(!is_array($haystack))
return False;
foreach($haystack as $key=>$value){
if(is_array($value)){
if(self::in_array_multi($needle, $value))
return True;
else
self::in_array_multi($needle, $value);
}
else
if(trim($value) === trim($needle)){//visibility fix//
error_log("$value === $needle setting visibility to 1 hidden");
return True;
}
}
return False;
}
you can use this function ;
https://github.com/serhatozles/ArrayAdvancedSearch
<?php
include('ArraySearch.php');
$query = "a='Example World' and b>='2'";
$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);
$Result = ArraySearch($Array,$query,1);
echo '<pre>';
print_r($Result);
echo '</pre>';
// Output:
// Array
// (
// [0] => Array
// (
// [a] => Example World
// [b] => 2
// )
//
// )
$a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];
$found = null;
$search = 'eee';
array_walk($a, function ($k, $v) use ($search, &$found) {
if (in_array($search, $k)) {
$found = $v;
}
});
var_dump($found);
Try this
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
?>
Just share, maybe can like this.
if( ! function_exists('arraySearchMulti')){
function arraySearchMulti($search,$key,$array,$returnKey=false)
{
foreach ($array as $k => $val) {
if (isset($val[$key])) {
if ((string)$val[$key] == (string)$search) {
return ($returnKey ? $k : $val);
}
}else{
return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);
}
}
return null;
}}
No one else has used array_reduce yet, so thought I'd add this approach...
$find_by_uid = '100';
$is_in_array = array_reduce($userdb, function($carry, $user) use ($find_by_uid){
return $carry ? $carry : $user['uid'] === $find_by_uid;
});
// Returns true
Gives you more fine control over the 'search' logic than array_search().
Note that I have used strict equality here but you could opt for different comparison logic. The $carry means the comparison needs to be true once, and the final result will be TRUE.
I was looking for functionality similar to that of MySQL LIKE %term%. Based on the answers on this page. I am able to search the JSON array from a file.
user_list.json looks as sample below:
{
"user-23456": {
"name": "John Doe",
"age": "20",
"email": "doe#sample.com",
"user_id": "23456"
},
"user-09876": {
"name": "Ronojoy Adams",
"age": "35",
"email": "joy#sample.com",
"user_id": "09876"
},
"user-34890": {
"name": "Will Artkin",
"age": "16",
"email": "will#sample.com",
"user_id": "34890"
},
}
/*
*search_key_like
*/
function search_key_like($value, $key, $array) {
$results=array();
$keyword = preg_quote($value, '~');
foreach ($array as $k => $val) {
//if name a is spell John and keyword is sent as joh or JOH it will return null
//to fix the issue convert the string into lowercase and uppercase
$data=array($val[$key],strtolower($val[$key]),strtoupper($val[$key]));
if (preg_grep('~' . $keyword . '~', $data)) {
array_push($results,$val[$key]);
}
}
return $results;
}
Usage===pulling the JSON file===
$user_list_json='./user_list.json';
if(file_exists($user_list_json) && file_get_contents($user_list_json)){
$file_json_data=file_get_contents($user_list_json);
$json_array_data=json_decode($file_json_data,true);
$user_name_like = search_key_like('ron', 'name', $json_array_data);
print "<pre>".print_r($user_name_like,true);
}
for( $i =0; $i < sizeof($allUsers); $i++)
{
$NEEDLE1='firstname';
$NEEDLE2='emailAddress';
$sterm='Tofind';
if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
{
$Fname= $allUsers[$i][$NEEDLE1];
$Lname= $allUsers[$i][$NEEDLE2];
$pos1 = stripos($Fname, $sterm);
$pos2=stripos($Lname, $sterm);//not case sensitive
if($pos1 !== false ||$pos2 !== false)
{$resultsMatched[] =$allUsers[$i];}
else
{ continue;}
}
}
Print_r($resultsMatched); //will give array for matched values even partially matched
With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.
Expanding on the function #mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
return $key;
}
}
return false;
}
For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"
If question i.e.
$a = [
[
"_id" => "5a96933414d48831a41901f2",
"discount_amount" => 3.29,
"discount_id" => "5a92656a14d488570c2c44a2",
],
[
"_id" => "5a9790fd14d48879cf16a9e8",
"discount_amount" => 4.53,
"discount_id" => "5a9265b914d488548513b122",
],
[
"_id" => "5a98083614d488191304b6c3",
"discount_amount" => 15.24,
"discount_id" => "5a92806a14d48858ff5c2ec3",
],
[
"_id" => "5a982a4914d48824721eafe3",
"discount_amount" => 45.74,
"discount_id" => "5a928ce414d488609e73b443",
],
[
"_id" => "5a982a4914d48824721eafe55",
"discount_amount" => 10.26,
"discount_id" => "5a928ce414d488609e73b443",
],
];
Ans:
function searchForId($id, $array) {
$did=0;
$dia=0;
foreach ($array as $key => $val) {
if ($val['discount_id'] === $id) {
$dia +=$val['discount_amount'];
$did++;
}
}
if($dia != '') {
echo $dia;
var_dump($did);
}
return null;
};
print_r(searchForId('5a928ce414d488609e73b443',$a));
Here is a better solution, in case your pulling data from a database or a multidimensional array
Example of a multidimensional array:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
function search_user_by_name($name, $array) {
foreach ($array as $keys) {
foreach ($keys as $key => $_user_record) {
if ($_user_record == $name) {
return [$key => $_user_record];//Return and array of user
}
}
}
return null;
}
Call the function:
$results = search_user_by_name('John', $records);
print_r($results);
Output: Array ( [first_name] => John )

Create a new array from a unknown depth multidimensional and keep the same structure

I have a multidimensional array that can have any depth. What im trying to do is to filter the whole path based on dynamic keys and create a new array of it.
Example of the array
$originalArray = [
"title" => "BACKPACK MULTICOLOUR",
"description" => "description here",
"images" => [
[
"id" => 12323123123,
"width" => 635,
"height" => 560,
"src" => "https://example.com",
"variant_ids": [32694976315473, 32863017926737],
],
[
"id" => 4365656656565,
"width" => 635,
"height" => 560,
"src" => "https://example.com",
"variant_ids": [32694976315473, 32863017926737],
]
],
"price" => [
"normal" => 11.00,
"discount" => [
"gold_members" => 9.00,
"silver_members" => 10.00,
"bronze_members" => null
]
]
];
Example how the output should look like with the key "title, width, height, gold_members" filtered out. Only keys from the end of the array tree should be valid, so nothing must happen when images is in the filter
$newArray = [
"title" => "BACKPACK MULTICOLOUR",
"images" => [
[
"width" => 635,
"height" => 560,
],
[
"width" => 635,
"height" => 560,
]
],
"price" => [
"discount" => [
"gold_members" => 9.00,
]
]
];
I guess that i should create a function that loop through each element and when it is an associative array, it should call itself again
Because the filtered paths are unknown i cannot make a hardcoded setter like this:
$newArray["images"][0]["width"] = 635
The following filter will be an example but it should basically be dynamic
example what i have now:
$newArray = handleArray($originalArray);
handleArray($array)
{
$filter = ["title", "width", "height", "gold_members"];
foreach ($array as $key => $value) {
if (is_array($value)) {
$this->handleArray($value);
} else {
if (in_array($key, $filter)) {
// put this full path in the new array
}
}
}
}
[Solved] Update:
I solved my problem thanks to #trincot
I used his code and added an extra check to add an array with multiple values to the new array
My code to solve the issue:
<?php
function isListOfValues($array) {
$listOfArrays = [];
foreach ($array as $key => $value) {
$listOfArrays[] = ! is_array($value) && is_int($key);
}
return array_sum($listOfArrays) === count($listOfArrays);
}
function filterKeysRecursive(&$arr, &$keep) {
$result = [];
foreach ($arr as $key => $value) {
if (is_array($value) && ! isListOfValues($value)) {
$value = filterKeysRecursive($value, $keep);
if (count($value)) {
$result[$key] = $value;
}
} else if (array_key_exists($key, $keep)) {
$result[$key] = $value;
}
}
return $result;
}
$keep = array_flip(["title", "width", "height", "gold_members"]);
$result = filterKeysRecursive($originalArray, $keep);
You could use a recursive function, with following logic:
base case: the value associated with a key is not an array (it is a "leaf"). In that case the new object will have that key/value only when the key is in the list of desired keys.
recursive case: the value associated with a key is an array. Apply recursion to that value. Only add the key when the returned result is not an empty array. In that case associate the filtered value to the key in the result object.
To speed up the look up in the list of keys, it is better to flip that list into an associative array.
Here is the implementation:
function filter_keys_recursive(&$arr, &$keep) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
$value = filter_keys_recursive($value, $keep);
if (count($value)) $result[$key] = $value;
} else if (array_key_exists($key, $keep)) {
$result[$key] = $value;
}
}
return $result;
}
$originalArray = ["title" => "BACKPACK MULTICOLOUR","description" => "description here","images" => [["id" => 12323123123,"width" => 635,"height" => 560,"src" => "https://example.com"],["id" => 4365656656565,"width" => 635,"height" => 560,"src" => "https://example.com"]],"price" => ["normal" => 11.00,"discount" => ["gold_members" => 9.00,"silver_members" => 10.00,"bronze_members" => null]]];
$keep = array_flip(["title", "width", "height", "gold_members"]);
$result = filter_keys_recursive($originalArray, $keep);
My proposition to you is to write a custom function to transform structure from one schema to another:
function transform(array $originalArray): array {
array_walk($originalArray['images'], function (&$a, $k) {
unset($a['id']); unset($a['src']);
});
unset($originalArray['description']);
unset($originalArray['price']['normal']);
unset($originalArray['price']['discount']['silver_members']);
unset($originalArray['price']['discount']['bronze_members']);
return $originalArray;
}
var_dump(transform($originalArray));
If you are familiar with OOP I suggest you to look at how DTO works in API Platform for example and inject this idea into your code by creating custom DataTransformers where you specify which kind of structers you want to support with transformer and a method where you transform one structure to another.
Iterate over the array recursively on each key and subarray.
If the current key in the foreach is a required key in the result then:
If the value is not an array, simply assign the value
If the value is an array, iterate further down over value recursively just in case if there is any other filtering of the subarray keys that needs to be done.
If the current key in the foreach is NOT a required key in the result then:
Iterate over value recursively if it's an array in itself. This is required because there could be one of the filter keys deep down which we would need. Get the result and only include it in the current subresult if it's result is not an empty array. Else, we can skip it safely as there are no required keys down that line.
Snippet:
<?php
function filterKeys($array, $filter_keys) {
$sub_result = [];
foreach ($array as $key => $value) {
if(in_array($key, $filter_keys)){// if $key itself is present in $filter_keys
if(!is_array($value)) $sub_result[$key] = $value;
else{
$temp = filterKeys($value, $filter_keys);
$sub_result[$key] = count($temp) > 0 ? $temp : $value;
}
}else if(is_array($value)){// if $key is not present in $filter_keys - iterate over the remaining subarray for that key
$temp = filterKeys($value, $filter_keys);
if(count($temp) > 0) $sub_result[$key] = $temp;
}
}
return $sub_result;
}
$result = filterKeys($originalArray, ["title", "width", "height", "gold_members"]);
print_r($result);
Online Demo
Try this way.
$expectedKeys = ['title','images','width','height','price','gold_members'];
function removeUnexpectedKeys ($originalArray,$expectedKeys)
{
foreach ($originalArray as $key=>$value) {
if(is_array($value)) {
$originalArray[$key] = removeUnexpectedKeys($value,$expectedKeys);
if(!is_array($originalArray[$key]) or count($originalArray[$key]) == 0) {
unset($originalArray[$key]);
}
} else {
if (!in_array($key,$expectedKeys)){
unset($originalArray[$key]);
}
}
}
return $originalArray;
}
$newArray = removeUnexpectedKeys ($originalArray,$expectedKeys);
print_r($newArray);
check this on editor,
https://www.online-ide.com/vFN69waXMf

How to get a value with keyword ID in the same array hierarchy level with PHP [duplicate]

I have an array where I want to search the uid and get the key of the array.
Examples
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'
)
);
The function call search_by_uid(100) (uid of first user) should return 0.
The function call search_by_uid(40489) should return 2.
I tried making loops, but I want a faster executing code.
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchForId('100', $userdb);
It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.
Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Here is documentation: http://php.net/manual/en/function.array-column.php.
If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.
If you want just one result:
$key = array_search(40489, array_column($userdb, 'uid'));
For multiple results
$keys = array_keys(array_column($userdb, 'uid'), 40489);
In case you have an associative array as pointed in the comments you could make it with:
$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!
Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!
In later versions of PHP (>= 5.5.0) you can use this one-liner:
$key = array_search('100', array_column($userdb, 'uid'));
Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Usage: $results = searcharray('searchvalue', searchkey, $array);
Looks array_filter will be suitable solution for this...
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
PHP Code
<?php
$search = 5465;
$found = array_filter($userdb,function($v,$k) use ($search){
return $v['uid'] == $search;
},ARRAY_FILTER_USE_BOTH); // With latest PHP third parameter is optional.. Available Values:- ARRAY_FILTER_USE_BOTH OR ARRAY_FILTER_USE_KEY
$values= print_r(array_values($found));
$keys = print_r(array_keys($found));
I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.
Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.
Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.
/**
* #param array multidimensional
* #param string value to search for, ie a specific field name like name_first
* #param string associative key to find it in, ie field_name
*
* #return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.
This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).
/**
* #param array multidimensional
* #param string $search_value The value to search for, ie a specific 'Taylor'
* #param string $key_to_search The associative key to find it in, ie first_name
* #param string $other_matching_key The associative key to find in the matches for employed
* #param string $other_matching_value The value to find in that matching associative key, ie true
*
* #return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Use of function
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Result
Array ( [0] => 2 )
You can do that with combination of two functions, array_search & array_column.
$search_value = '5465';
$search_key = 'uid';
$user = array_search($search_value, array_column($userdb, $search_key));
print_r($userdb[$user]);
5465 is the user ID you want to search, uid is the key that contains user ID and $userdb is the array that is defined in the question.
References:
array_search on php.net
array_column on php.net
I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:
$arr = array(
'XXX'=>array(
'YYY'=> array(
'AAA'=> array(
'keyN' =>'value1'
)
),
'ZZZ'=> array(
'BBB'=> array(
'keyN' => 'value2'
)
)
//.....
)
);
$result = searchItemsByKey($arr,'keyN');
print '<pre>';
print_r($result);
print '<pre>';
// OUTPUT
Array
(
[0] => value1
[1] => value2
)
Function code:
function searchItemsByKey($array, $key)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key)
$results[] = $array[$key];
foreach ($array as $sub_array)
$results = array_merge($results, searchItemsByKey($sub_array, $key));
}
return $results;
}
Here is one liner for the same,
$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];
Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if ($val[$sKey] == $id) {
return $key;
}
}
return false;
}
Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.
// Array Data Of Users
$userdb = array (
array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);
// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
echo "Search Result can not be found";
}
PHP Fiddle Example
I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not
$arr = array(
array(
'title' => 'abc'
)
);
Then i can use this
$res = array_search('abc', array_column($arr, 'title'));
if($res == ''){
echo 'exists';
} else {
echo 'notExists';
}
I think This is the Most simple way to define
I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:
function search_in_array_r($needle, $array) {
$found = array();
foreach ($array as $key => $val) {
if ($val[1] == $needle) {
array_push($found, $val[1]);
}
}
if (count($found) != 0)
return $found;
else
return null;
}
/**
* searches a simple as well as multi dimension array
* #param type $needle
* #param type $haystack
* #return boolean
*/
public static function in_array_multi($needle, $haystack){
$needle = trim($needle);
if(!is_array($haystack))
return False;
foreach($haystack as $key=>$value){
if(is_array($value)){
if(self::in_array_multi($needle, $value))
return True;
else
self::in_array_multi($needle, $value);
}
else
if(trim($value) === trim($needle)){//visibility fix//
error_log("$value === $needle setting visibility to 1 hidden");
return True;
}
}
return False;
}
you can use this function ;
https://github.com/serhatozles/ArrayAdvancedSearch
<?php
include('ArraySearch.php');
$query = "a='Example World' and b>='2'";
$Array = array(
'a' => array('d' => '2'),
array('a' => 'Example World','b' => '2'),
array('c' => '3'), array('d' => '4'),
);
$Result = ArraySearch($Array,$query,1);
echo '<pre>';
print_r($Result);
echo '</pre>';
// Output:
// Array
// (
// [0] => Array
// (
// [a] => Example World
// [b] => 2
// )
//
// )
$a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];
$found = null;
$search = 'eee';
array_walk($a, function ($k, $v) use ($search, &$found) {
if (in_array($search, $k)) {
$found = $v;
}
});
var_dump($found);
Try this
<?php
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) &&
recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
?>
Just share, maybe can like this.
if( ! function_exists('arraySearchMulti')){
function arraySearchMulti($search,$key,$array,$returnKey=false)
{
foreach ($array as $k => $val) {
if (isset($val[$key])) {
if ((string)$val[$key] == (string)$search) {
return ($returnKey ? $k : $val);
}
}else{
return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);
}
}
return null;
}}
No one else has used array_reduce yet, so thought I'd add this approach...
$find_by_uid = '100';
$is_in_array = array_reduce($userdb, function($carry, $user) use ($find_by_uid){
return $carry ? $carry : $user['uid'] === $find_by_uid;
});
// Returns true
Gives you more fine control over the 'search' logic than array_search().
Note that I have used strict equality here but you could opt for different comparison logic. The $carry means the comparison needs to be true once, and the final result will be TRUE.
I was looking for functionality similar to that of MySQL LIKE %term%. Based on the answers on this page. I am able to search the JSON array from a file.
user_list.json looks as sample below:
{
"user-23456": {
"name": "John Doe",
"age": "20",
"email": "doe#sample.com",
"user_id": "23456"
},
"user-09876": {
"name": "Ronojoy Adams",
"age": "35",
"email": "joy#sample.com",
"user_id": "09876"
},
"user-34890": {
"name": "Will Artkin",
"age": "16",
"email": "will#sample.com",
"user_id": "34890"
},
}
/*
*search_key_like
*/
function search_key_like($value, $key, $array) {
$results=array();
$keyword = preg_quote($value, '~');
foreach ($array as $k => $val) {
//if name a is spell John and keyword is sent as joh or JOH it will return null
//to fix the issue convert the string into lowercase and uppercase
$data=array($val[$key],strtolower($val[$key]),strtoupper($val[$key]));
if (preg_grep('~' . $keyword . '~', $data)) {
array_push($results,$val[$key]);
}
}
return $results;
}
Usage===pulling the JSON file===
$user_list_json='./user_list.json';
if(file_exists($user_list_json) && file_get_contents($user_list_json)){
$file_json_data=file_get_contents($user_list_json);
$json_array_data=json_decode($file_json_data,true);
$user_name_like = search_key_like('ron', 'name', $json_array_data);
print "<pre>".print_r($user_name_like,true);
}
for( $i =0; $i < sizeof($allUsers); $i++)
{
$NEEDLE1='firstname';
$NEEDLE2='emailAddress';
$sterm='Tofind';
if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])
{
$Fname= $allUsers[$i][$NEEDLE1];
$Lname= $allUsers[$i][$NEEDLE2];
$pos1 = stripos($Fname, $sterm);
$pos2=stripos($Lname, $sterm);//not case sensitive
if($pos1 !== false ||$pos2 !== false)
{$resultsMatched[] =$allUsers[$i];}
else
{ continue;}
}
}
Print_r($resultsMatched); //will give array for matched values even partially matched
With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.
Expanding on the function #mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:
function searchArrayKeyVal($sKey, $id, $array) {
foreach ($array as $key => $val) {
if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false) {
return $key;
}
}
return false;
}
For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"
If question i.e.
$a = [
[
"_id" => "5a96933414d48831a41901f2",
"discount_amount" => 3.29,
"discount_id" => "5a92656a14d488570c2c44a2",
],
[
"_id" => "5a9790fd14d48879cf16a9e8",
"discount_amount" => 4.53,
"discount_id" => "5a9265b914d488548513b122",
],
[
"_id" => "5a98083614d488191304b6c3",
"discount_amount" => 15.24,
"discount_id" => "5a92806a14d48858ff5c2ec3",
],
[
"_id" => "5a982a4914d48824721eafe3",
"discount_amount" => 45.74,
"discount_id" => "5a928ce414d488609e73b443",
],
[
"_id" => "5a982a4914d48824721eafe55",
"discount_amount" => 10.26,
"discount_id" => "5a928ce414d488609e73b443",
],
];
Ans:
function searchForId($id, $array) {
$did=0;
$dia=0;
foreach ($array as $key => $val) {
if ($val['discount_id'] === $id) {
$dia +=$val['discount_amount'];
$did++;
}
}
if($dia != '') {
echo $dia;
var_dump($did);
}
return null;
};
print_r(searchForId('5a928ce414d488609e73b443',$a));
Here is a better solution, in case your pulling data from a database or a multidimensional array
Example of a multidimensional array:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);
function search_user_by_name($name, $array) {
foreach ($array as $keys) {
foreach ($keys as $key => $_user_record) {
if ($_user_record == $name) {
return [$key => $_user_record];//Return and array of user
}
}
}
return null;
}
Call the function:
$results = search_user_by_name('John', $records);
print_r($results);
Output: Array ( [first_name] => John )

Specific problem with traversing an array in php

I have given the array:
array(
"firstName": null,
"lastName": null,
"category": [
"name": null,
"service": [
"foo" => [
"bar" => null
]
]
]
)
that needs to be transform into this:
array(
0 => "firstName",
1 => "lastName",
2 => "category",
"category" => [
0 => "name",
1 => "service",
"service" => [
0 => "foo",
"foo" => [
0 => "bar"
]
]
]
)
The loop should check if a value is an array and if so, it should add the key as a value (0 => category) to the root of array and then leave the key as it is (category => ...) and traverse the value again to build the tree as in example.
I am stuck with this and every time I try, I get wrong results. Is there someone who is array guru and knows how to simply do it?
The code so far:
private $array = [];
private function prepareFields(array $fields):array
{
foreach($fields as $key => $value)
{
if(is_array($value))
{
$this->array[] = $key;
$this->array[$key] = $this->prepareFields($value);
}
else
{
$this->array[] = $key;
}
}
return $this->array;
}
You could make use of array_reduce:
function prepareFields(array $array): array
{
return array_reduce(array_keys($array), function ($result, $key) use ($array) {
$result[] = $key;
if (is_array($array[$key])) {
$result[$key] = prepareFields($array[$key]);
}
return $result;
});
}
Demo: https://3v4l.org/3BfKD
You can do it with this, check the Demo
function array_format(&$array){
$temp_array = [];
foreach($array as $k=>$v){
$temp_array[] = $k;
if(is_array($v)){
array_format($v);
$temp_array[$k] = $v;
}
}
$array = $temp_array;
}
array_format($array);
print_r($array);

Categories