array_filter with assoc array? - php

I am using array_filter to do something like this:
function endswithy($value) {
return (substr($value, -1) == 'y');
}
$people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
$withy = array_filter($people, "endswithy");
var_dump($withy);
BUT with the more option in filter for example
$people = array(
"Johnny"=>array("year"=>1989, "job"=>"prof"),
"Timmy"=>array("year"=>1989, "job"=>"std"),
"Bobby"=>array("year"=>1988),
"Sam"=>array("year"=>1983),
"Tammy"=>array("year"=>1985),
"Danny"=>array("year"=>1983),
"Joe"=>array("year"=>1989,"job"=>"prof"));
OR
$people = array(
array("name"=>"Johnny","year"=>1989, "job"=>"prof"),
array("name"=>"Timmy","year"=>1989, "job"=>"std"),
array("name"=>"Bobby""year"=>1988),
array("name"=>"Sam","year"=>1983),
array("name"=>"Tammy","year"=>1985),
array("name"="Danny","year"=>1983),
array("name"="Joe","year"=>1989,"job"=>"prof"));
How Can I got the only this people (endwith y and year=1989 and job=prof) ,Can I use array_filter?
or any build-in function to do this?
$people = array(
"Johnny"=>array("year"=>1989, "job"=>"prof")
);
OR
$people = array(
array("name="Johnny","year"=>1989, "job"=>"prof")
);

PHP 5.6 introduces the optional flag ARRAY_FILTER_USE_KEY that will allow this:
function endswithy($name) {
return (substr($name, -1) == 'y');
}
$people = array(
"Johnny"=>array("year"=>1989, "job"=>"prof"),
"Timmy"=>array("year"=>1989, "job"=>"std"),
"Bobby"=>array("year"=>1988),
"Sam"=>array("year"=>1983),
"Tammy"=>array("year"=>1985),
"Danny"=>array("year"=>1983),
"Joe"=>array("year"=>1989,"job"=>"prof")
);
$peopleEndingInY = array_filter($people, 'endswithy', ARRAY_FILTER_USE_KEY);
// Outputs: 5
var_dump(count($peopleEndingInY));
If you need to maintain and key and the value, another flag ARRAY_FILTER_USE_BOTH will do that as seen in this example:
$ar = array(
'key1' => 'value1',
'key2' => 'value2'
);
//Note that this doens't actually filter anything since it doesn't return a bool.
$output = array_filter($ar, function($value, $key){
echo sprintf("%s => %s\n", $key, $value);
}, ARRAY_FILTER_USE_BOTH);

Either use foreach with your current array's structure:
$people = array(
"Johnny" => array("year" => 1989, "job" => "prof"),
"Timmy" => array("year" => 1989, "job" => "std"),
"Bobby" => array("year" => 1988),
"Sam" => array("year" => 1983),
"Tammy" => array("year" => 1985),
"Danny" => array("year" => 1983),
"Joe" => array("year" => 1989, "job" => "prof"),
);
foreach ( $people as $name => $info ) {
if ( substr($name, -1) !== 'y' || $info['year'] != 1989 ) {
unset($people[$name]);
}
}
print_r($people);
// output:
Array
(
[Johnny] => Array
(
[year] => 1989
[job] => prof
)
[Timmy] => Array
(
[year] => 1989
[job] => std
)
)
Or convert your array so that name is value of inner array:
$people = array(
array('name' => 'Johnny', 'year' => 1989, 'job' => 'prof'),
array('name' => 'Timmy' , 'year' => 1989, 'job' => 'std'),
array('name' => 'Bobby' , 'year' => 1988),
array('name' => 'Sam' , 'year' => 1983),
array('name' => 'Tammy' , 'year' => 1985),
array('name' => 'Danny' , 'year' => 1983),
array('name' => 'Joe' , 'year' => 1989, 'job' => 'prof'),
);
function filter($item) {
return substr($item['name'], -1) === 'y' && $item['year'] == 1989;
}
$filteredPeople = array_filter($people, 'filter');
print_r($filteredPeople);
// output:
Array
(
[0] => Array
(
[name] => Johnny
[year] => 1989
[job] => prof
)
[1] => Array
(
[name] => Timmy
[year] => 1989
[job] => std
)
)

Related

Compare and combine multidimensional array then sort descending PHP

I have 2 multi arrays, profiles and encoded arrays like this
$profiles = array(
array(
'user_id' => 'fcc3d884-fbef-438a-9c86-0ad52c9b1223',
'first_name' => 'Narñia',
'middle_name' => 'Ñ',
'last_name' => 'Cruz',
'ext' => ''
),
array(
'user_id' => '0d31557d-1e9f-4db3-ac0d-72e1709fe89c',
'first_name' => 'Randy',
'middle_name' => 'O',
'last_name' => 'Rocker',
'ext' => ''
),
array(
'user_id' => '0f93f169-cf56-49df-a76b-7596446104c6',
'first_name' => 'Qwerty',
'middle_name' => 'K',
'last_name' => 'Asdfg',
'ext' => ''
),
array(
'user_id' => '23b1f4a2-034c-43b4-96b7-3191d78cead1',
'first_name' => 'Johny',
'middle_name' => 'L',
'last_name' => 'Walker',
'ext' => ''
)
);
$encoded = array(
array(
'encoder_id' => '0d31557d-1e9f-4db3-ac0d-72e1709fe89c',
'fullname' => 'Randy O. Rocker',
'encoded' => 10,
),
array(
'encoder_id' => '23b1f4a2-034c-43b4-96b7-3191d78cead1',
'fullname' => 'John L. Walker',
'encoded' => 20,
)
);
Now i want to get some data from $profiles then combine to $encoded array when user_id and encoder_id is match, i have this code but it seems wrong it only gets "John L. Waler" data. here's my code.
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
foreach($encoded as $k => $v){
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($v['encoder_id'] == $user_id) ? $v['encoder_id'] : $user_id,
'fullname' => ($v['encoder_id'] == $user_id) ? $v['fullname'] : $fullname,
'encoded' => ($v['encoder_id'] == $user_id) ? $v['encoded'] : 0
);
}
}
echo '<pre>';
print_r($data);
echo '</pre>';
here's the result
Array
(
[0] => Array
(
[id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
[fullname] => Narñia �. Cruz
[encoded] => 0
)
[1] => Array
(
[id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
[fullname] => Randy O. Rocker
[encoded] => 0 //this should be 10
)
[2] => Array
(
[id] => 0f93f169-cf56-49df-a76b-7596446104c6
[fullname] => Qwerty K. Asdfg
[encoded] => 0
)
[3] => Array
(
[id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
[fullname] => John L. Walker
[encoded] => 20
)
)
Also after combining them to a new array. i want to sort the new array by "encoded" attribute descending.
Thank you for understanding
You can make your life easier by re-indexing the $encoded array by the encoder_id values using array_column; then you don't have to search the array each time to look for a user_id value, you can just use isset. Once you've extracted your data, you can use usort to sort by the encoded values:
$encoded_ids = array_column($encoded, null, 'encoder_id');
$data = array();
foreach ($profiles as $profile) {
$user_id = $profile['user_id'];
if (isset($encoded_ids[$user_id])) {
$data[] = array('id' => $user_id,
'fullname' => $encoded_ids[$user_id]['fullname'],
'encoded' => $encoded_ids[$user_id]['encoded']
);
}
else {
$data[] = array('id' => $user_id,
'fullname' => "${profile['first_name']} ${profile['middle_name']} ${profile['last_name']}",
'encoded' => 0
);
}
}
usort($data, function ($a, $b) { return $b['encoded'] - $a['encoded'];});
print_r($data);
Output:
Array
(
[0] => Array
(
[id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
[fullname] => John L. Walker
[encoded] => 20
)
[1] => Array
(
[id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
[fullname] => Randy O. Rocker
[encoded] => 10
)
[2] => Array
(
[id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
[fullname] => Narñia Ñ Cruz
[encoded] => 0
)
[3] => Array
(
[id] => 0f93f169-cf56-49df-a76b-7596446104c6
[fullname] => Qwerty K Asdfg
[encoded] => 0
)
)
Demo on 3v4l.org
An alternative to Nick's version, using array_reduce:
$encodedByEncoderId = array_column($encoded, null, 'encoder_id');
$combined = array_reduce($profiles, function (array $combined, array $profile) use ($encodedByEncoderId): array {
$combined[] = [
'id' => $profile['user_id'],
'fullname' => $encodedByEncoderId[$profile['user_id']]['fullname']
?? "{$profile['first_name']} {$profile['middle_name']}. {$profile['last_name']}",
'encoded' => $encodedByEncoderId[$profile['user_id']]['encoded']
?? 0
];
return $combined;
}, []);
Demo: https://3v4l.org/kKBru
Try this!
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
$is_matched = 0;
$encoded_data = [];
foreach($encoded as $k => $v){
if ($user_id == $v['encoder_id']) {
$is_matched = 1;
$encoded_data = $v;
}
}
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($is_matched == 1) ? $encoded_data['encoder_id'] : $user_id,
'fullname' => ($is_matched == 1) ? $encoded_data['fullname'] : $fullname,
'encoded' => ($is_matched == 1) ? $encoded_data['encoded'] : 0
);
}

calculate the difference between two array

In PHP, how can I compare two array and get result in a third array ?
This result must contain old and new values. The goal is to display an HTML table with a header like "field | old value | new value" as this, the user can compare all values one by one.
First array :
$array1 = array(
'key1' => array(
'key1.1' => 'value',
'key1.2' => 'value',
),
'key2' => array(
'key2.1' => 'value',
'key2.2' => 'value',
),
'key3' => array(
array('key3.1' => 'value'),
array('key3.2' => 'value'),
),
);
Second array :
$array2 = array(
'key1' => array(
'key1.1' => 'value',
'key1.2' => 'value',
),
'key2' => array(
'key2.1' => 'value',
'key2.2' => 'value',
),
'key3' => array(
array('key3.1' => 'value'),
array('key3.2' => 'value'),
),
);
What I expect :
$results = array(
'key1' => array(
'key1.1' => array(
'old' => 'old_value',
'new' => 'new_value',
),
'key1.2' => array(
'old' => 'old_value',
'new' => 'new_value',
),
),
'key2' => array(
'key2.1' => array(
'old' => 'old_value',
'new' => 'new_value',
),
'key2.2' => array(
'old' => 'old_value',
'new' => 'new_value',
),
),
'key3' => array(
array(
'key3.1' => array(
'old' => 'old_value',
'new' => 'new_value')
),
array(
'key3.1' => array(
'old' => 'old_value',
'new' => 'new_value'),
)
),
);
What I have already tried without success :
function array_diff_assoc_recursive($array1, $array2) {
$exclude = array(
'custom_key'
);
$difference = array();
foreach($array1 as $key => $value) {
if(is_array($value)){
if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
if(!in_array($key,$exclude)){
$difference[$key]['old'] = $value;
$difference[$key]['new'] = $array2[$key];
}
} else {
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if(!empty($new_diff))
$difference[$key] = $new_diff;
}
} else if(!array_key_exists($key,$array2) || $array2[$key] !== $value) {
if(!in_array($key,$exclude)){
$difference[$key]['old'] = $value;
$difference[$key]['new'] = $array2[$key];
}
}
}
return $difference;
}
try this code, i'm sure this will work for you
<?php
echo "<pre>";
$array1 = array(
'key1' => array(
'key1.1' => 'aaa',
'key1.2' => 'xxx',
'key1.3' => 'vvv',
),
'key2' => array(
'key2.1' => 'eee',
'key2.2' => 'fff',
'key2.3' => 'ggg',
),
) ;
echo "Array 1: </br>";
print_r($array1);
$array2 = array(
'key1' => array(
'key1.1' => 'aaa',
'key1.2' => 'ddd',
'key1.3' => 'ccc',
),
'key2' => array(
'key2.1' => 'hhh',
'key2.2' => 'fff',
'key2.3' => 'ttt',
),
);
echo "Array 2:</br>";
print_r($array2);
$result='';
foreach($array1 as $key=> $val)
{
foreach($val as $k=> $v)
{
if($v != $array2[$key][$k])
{
$result[$key][$k]['old']= $array2[$key][$k] ;
$result[$key][$k]['new']= $v;
}
}
}
echo "Compared Result: </br>";
echo "<pre>"; print_r($result);
?>
This will Output
Array 1:
Array
(
[key1] => Array
(
[key1.1] => aaa
[key1.2] => xxx
[key1.3] => vvv
)
[key2] => Array
(
[key2.1] => eee
[key2.2] => fff
[key2.3] => ggg
)
)
Array 2:
Array
(
[key1] => Array
(
[key1.1] => aaa
[key1.2] => ddd
[key1.3] => ccc
)
[key2] => Array
(
[key2.1] => hhh
[key2.2] => fff
[key2.3] => ttt
)
)
Compared Result:
Array
(
[key1] => Array
(
[key1.2] => Array
(
[old] => ddd
[new] => xxx
)
[key1.3] => Array
(
[old] => ccc
[new] => vvv
)
)
[key2] => Array
(
[key2.1] => Array
(
[old] => hhh
[new] => eee
)
[key2.3] => Array
(
[old] => ttt
[new] => ggg
)
)
)
Prepare arrays using array_walk_recursive, and combine them. Please note that the original arrays will be changed
array_walk_recursive($array1, function(&$i) { if(!is_array($i)) $i = array('old'=> $i); });
array_walk_recursive($array2, function(&$i) { if(!is_array($i)) $i = array('new'=> $i); });
print_r(array_merge_recursive($array1, $array2));
demo

how to sort just a part from a multidimensional array? [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 7 years ago.
i have a multiple array.. the output looks like this:
Array
(
[0] => Array
(
[0] => AdsBot
[1] => 7
)
[1] => Array
(
[0] => SurveyBot
[1] => 1
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => bot
[1] => 27
)
what i need now is to sort arrays by there number.. so it should look exactly like this:
Array
(
[0] => Array
(
[0] => bot
[1] => 27
)
[1] => Array
(
[0] => AdsBot
[1] => 7
)
[2] => Array
(
[0] => bingbot
[1] => 3
)
[3] => Array
(
[0] => SurveyBot
[1] => 1
)
i need to sort it by the numbers array key.. but i really dont know how- well, i'm new to php
the multi. array code :
$bot_array = [
['name' => 'bingbot', 'number' => $bingbot],
['name' => 'googlebot', 'number' => $googlebot],
['name' => 'robots.txt', 'number' => $robots_txt],
['name' => 'exabot', 'number' => $exabot],
['name' => 'bot', 'number' => $bot],
['name' => 'robot', 'number' => $robot],
['name' => 'BaiDuSpider', 'number' => $BaiDuSpider],
['name' => 'Yahoo Slurp', 'number' => $yahoo_slurp],
['name' => 'AdsBot', 'number' => $adsbot],
['name' => 'SurveyBot', 'number' => $surveybot],
['name' => 'scanner', 'number' => $scanner],
['name' => 'checker', 'number' => $checker],
];
or maybe there is a more smarter way to do this?
i need this for a top ten :) on the left should be written all the names and at the right the quantity
thanks for any help :)
EDIT:
$tmp = Array();
foreach($bot_array as &$ba)
$tmp[] = &$ba["number"];
array_multisort($tmp, $bot_array);
foreach($bot_array as &$ba)
echo $ba["number"]."<br/>";
i did this but it still doesnt sort it like i want it..
0
0
0
1
10
12
27
3
3
5
7
9
this is what it gives me now :o
you can use this function
function sortAscending($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] < $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
You can use usort
<?php
$data = array(
array('AdsBot', 7),
array('SurveyBot', 1),
array('bingbot', 3),
array('bot', 27)
);
usort($data, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1[1] <= $val2[1]) {
return 1;
}
}
return -1;
}
var_dump($data);
Output
array(4) {
[0] =>
array(2) {
[0] =>
string(3) "bot"
[1] =>
int(27)
}
[1] =>
array(2) {
[0] =>
string(6) "AdsBot"
[1] =>
int(7)
}
[2] =>
array(2) {
[0] =>
string(7) "bingbot"
[1] =>
int(3)
}
[3] =>
array(2) {
[0] =>
string(9) "SurveyBot"
[1] =>
int(1)
}
}
According to your updated question, it should be.
<?php
usort($bot_array, 'botSort');
function botSort($val1, $val2) {
if (is_array($val1) && is_array($val2)) {
if ($val1['number'] <= $val2['number']) {
return 1;
}
}
return -1;
}
print_r($data);
Use this way to sort your array
$arry = array( array('AdsBot','7'),
array('SurveyBot','1'),
array('bingbot','3'),
array('bot','27')
);
echo "<pre>"; print_r($arry); echo "</pre>";
function sortByOrder($a, $b) {
return $a['1'] - $b['1'];
}
usort($arry, 'sortByOrder');
echo "<pre>"; print_r($arry); echo "</pre>";
Please, see bellow code.
$arr = array(
0 => array(
'0' => 'AdsBot',
'1' => 7
),
1 => array(
'0' => 'SurveyBot',
'1' => 1
),
2 => array(
'0' => 'bingbot',
'1' => 3
),
3 => array(
'0' => 'bot',
'1' => 27
)
);
echo '<pre>';
print_r(sortDescOrder($arr,'1'));
echo '</pre>';
function sortDescOrder($accounts, $key)
{
$ascending = function($accountA, $accountB) use ($key) {
if ($accountA[$key] == $accountB[$key]) {
return 0;
}
return ($accountA[$key] > $accountB[$key]) ? -1 : 1;
};
usort($accounts, $ascending);
return $accounts;
}
Or see another code
$bot_array = [
['name' => 'bingbot', 'number' => 5],
['name' => 'googlebot', 'number' => 8],
['name' => 'robots.txt', 'number' => 3],
['name' => 'exabot', 'number' => 7],
['name' => 'bot', 'number' => 7],
['name' => 'robot', 'number' => 12],
['name' => 'BaiDuSpider', 'number' => 45],
['name' => 'Yahoo Slurp', 'number' => 18],
['name' => 'AdsBot', 'number' => 78],
['name' => 'SurveyBot', 'number' => 96],
['name' => 'scanner', 'number' => 41],
['name' => 'checker', 'number' => 10]
];
usort($bot_array, function($x, $y) {
return $x['number'] <= $y['number'];
});
echo '<pre>';
print_r($bot_array);
echo '</pre>';
Try usort(). It allows you to define a callback to sort on a custom expression. In your case you want to reverse sort by the second indexed element in each sub-array:
<?php
$bots = [
[
'name' => 'AdsBot',
'number' => 7,
],
[
'name' => 'SurveyBot',
'number' => 1,
],
[
'name' => 'bingbot',
'number' => 3,
],
[
'name' => 'bot',
'number' => 27,
],
];
usort($bots, function($a, $b) {
return $a['number'] <= $b['number'];
});
print_r($bots);
Yields:
Array
(
[0] => Array
(
[name] => bot
[number] => 27
)
[1] => Array
(
[name] => AdsBot
[number] => 7
)
[2] => Array
(
[name] => bingbot
[number] => 3
)
[3] => Array
(
[name] => SurveyBot
[number] => 1
)
)
Hope this helps :)

Find duplicate array values and delete conditionally

I have an multidimensional array like this:
$orders = array(
array(
'id' => '123',
'name' => 'John',
'lastname'=>'Carter',
'rate' => '1.0'
),
array(
'id' => '546',
'name' => 'Ben',
'lastname'=>'Wall',
'rate' => '0.25'
),
array(
'id' => '666',
'name' => 'John Bow',
'lastname'=>'Porter',
'rate' => '0.25'
),
array(
'id' => '156',
'name' => 'John',
'lastname'=>'Carter',
'rate' => '0.5'
)
);
and want make a function that will be delete duplicate rows that rate < 1.0. The result array should be:
$orders = array(
array(
'id' => '123',
'name' => 'John',
'lastname'=>'Carter',
'rate' => '1.0'
),
array(
'id' => '546',
'name' => 'Ben',
'lastname'=>'Wall',
'rate' => '0.25'
),
array(
'id' => '666',
'name' => 'John',
'lastname'=>'Porter',
'rate' => '0.25'
)
);
Not very beautiful and speed, but workable solution:
$a = array(...); // Your array
$hashstack = array_map(function($value) { return md5($value['name'] . $value['lastname']); }, $a);
$result = array_filter($a, function($value) use ($hashstack)
{
if ((float)$value['rate'] < 1.0) {
$count = 0;
foreach ($hashstack as $hash) {
if (md5($value['name'] . $value['lastname']) == $hash) {
$count++;
}
}
if ($count > 1) {
unset($value);
return;
}
}
return $value;
});
Result is the same of yours.
Edit: Second and good version here: http://ideone.com/zJ8vj
What do You mean by 'duplicated' - same 'rate' ?
Bellow example remove duplicated orders with same 'rate' and 'rate' < 1.0.
Is this what You need ?
$tmpOrders = array();
foreach($orders as $order) {
// Check only rate < 1.0
if((float)$order['rate'] < 1.0) {
// Check duplicate
$exists = false;
foreach($tmpOrders as $tmp) {
if($tmp['rate'] == $order['rate']) {
$exists = true;
break;
}
}
// Add if rate not exists
if(!$exists) {
$tmpOrders[] = $order;
}
}
// Add all with rate >= 1.0
else {
$tmpOrders[] = $order;
}
}
$orders = $tmpOrders;
echo "<pre>";
print_r($orders);
echo "<pre>";
Result:
Array
(
[0] => Array
(
[id] => 123
[name] => John
[lastname] => Carter
[rate] => 1.0
)
[1] => Array
(
[id] => 546
[name] => Ben
[lastname] => Wall
[rate] => 0.25
)
[2] => Array
(
[id] => 156
[name] => John
[lastname] => Carter
[rate] => 0.5
)
)

Searching in a multi-dimensional array (PHP)

I'm having a problem lately that's driving me crazy. I have a multi-dimensional array like this:
$a = array(
'db' => array(
'0' => array(
'id' => '1',
'name' => 'test',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
),
'1' => array(
'id' => '2',
'name' => 'test2',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
)
'2' => array(
'id' => '3',
'name' => 'test',
'cat' => array(
'a' => '50',
'b' => '40',
'c' => '90'
),
'canvas' => '1'
)
)
);
And i want to search on it using a function like this: search('canvas = 1');
That would return all the arrays, child of db, that have a key canvas with the value of 1. Or, for example:
search('a = 15');
Would return all arrays that have a key, child of cat, named a and with a value of 15.
$a = array(
'db' => array(
'0' => array(
'id' => '1',
'name' => 'test',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
),
'1' => array(
'id' => '2',
'name' => 'test2',
'cat' => array(
'a' => '15',
'b' => '20',
'c' => '30'
),
'canvas' => '2'
),
)
);
//checks if array $array contains element with $searchKey key, and $searchVal value
function arrayContains($array, $searchVal, $searchKey) {
if (!is_array($array))
return false;
foreach ($array as $key => $value) {
if ($key === $searchKey && $searchVal === $value)
return true;
if (is_array($value) && arrayContains($value, $searchVal, $searchKey))
return true;
}
return false;
}
function search($a, $search) {
list($searchKey, $searchVal) = explode('=', $search);
$result = array();
foreach($a as $val) {
if (arrayContains($val, $searchVal, $searchKey))
$result[] = $val;
}
return $result;
}
print_r(search($a['db'], "a=15"));
print_r(search($a['db'], "canvas=1"));
Which produces this output(outputs sub-arrays of $a['db'] which contain searched key=>value pair):
Array
(
[0] => Array
(
[id] => 1
[name] => test
[cat] => Array
(
[a] => 15
[b] => 20
[c] => 30
)
[canvas] => 2
)
[1] => Array
(
[id] => 2
[name] => test2
[cat] => Array
(
[a] => 15
[b] => 20
[c] => 30
)
[canvas] => 2
)
)
Array
(
[0] => Array
(
[id] => 3
[name] => test
[cat] => Array
(
[a] => 50
[b] => 40
[c] => 90
)
[canvas] => 1
)
)
Just check the below link if this can help you -
http://php.net/manual/en/function.array-search.php
It contains detailed documentation of php function array_search() and various user codes for searching in multi-dimensional array along with user reviews.
function search($array, $canvas)
{
$result = array();
foreach ($array as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
if ($v2['canvas'] == $canvas) {
$result[] = $array[$k1][$k2];
}
}
}
return $result;
}
// $a = your array
print_r(search($a, 1));

Categories