I get some data from the database, which is saved in "$Data". $Data looks like this:
[Data] => Array
(
[0] => Array
(
[PrinterID] => 3
[PrinterName] => PRT03_EDV
[isDefaultPrinter] => 1
[isMapped] => 0
)
[1] => Array
(
[PrinterID] => 1
[PrinterName] => PRT01_Zentral
[isDefaultPrinter] => 0
[isMapped] => 1
)
[2] => Array
(
[PrinterID] => 2
[PrinterName] => PRT02_BH
[isDefaultPrinter] => 0
[isMapped] => 0
)
I need to verify, that there is no array in $Data, where "isDefaultPrinter == True" and "isMapped == False". Programatically:
if ( $Data["isDefaultPrinter"] == true and $Data["isMapped"] == false ) {
// Remove from Array
}
I did start to code this on my own based on this and my result was a terrible looking nested loop, which did not work :-(
I am a beginner and I wanted to ask, if there is an nice and easy way to do this?
Thank you
Here's a version using array_filter, which is sort of built for this. See http://php.net/manual/en/function.array-filter.php
$valid = array_filter($Data, function($var) {
return !($var['isDefaultPrinter'] && !$var['isMapped']);
});
Use foreach to loop over the data array:
foreach ($Data['Data'] as $entry) {
// Examine every entry
if ($entry['isDefaultPrinter'] && !$entry['isMapped']) {
// $entry does not meet criteria
}
}
You can write a function that verifies that every entry meets your criteria:
function validateData($Data) {
foreach ($Data['Data'] as $entry) {
// Examine every entry
if ($entry['isDefaultPrinter'] && !$entry['isMapped']) {
// $entry does not meet criteria
return false;
}
}
// Everything is OK
return true;
}
var_dump(validateData($Data));
You can use unset to remove the row of the array that doesn't fit your "keep" criteria. You need to know the array key to remove it tidily; this foreach with the $key value as well:
foreach ($var['Data'] as $key => $entry) {
// Examine every entry
if ($entry['isDefaultPrinter'] && !$entry['isMapped']) {
// $entry does not meet criteria
unset($var['Data'][$key]);
}
}
print_r($var); //output remaining values.
Once completed - and if you wish - you can then reindex the [outer] array using array_values():
$var['Data'] = array_values($var['Data']);
Related
I have the following array:
Array
(
[0] => Array
(
[CODE] => OK
[company_id] => 170647449000
[taxnumber] => 944703420
[name] => SOME NAME
[title] => S.A
)
[1] => Array
(
[CODE] => OK
[company_id] => 17063649000
[taxnumber] => 999033420
[name] => SOME OTHER NAME
[title] => ANOTHER DIFFERENT TITLE
)
)
If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.
I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:
function myfunction($agents, $field, $value)
{
foreach($agents as $key => $agent)
{
if ( $agent[$field] === $value )
return $key;
}
return false;
}
I always get false, even I am sending the value that exists.
Replace return $key with return $agent and operator === with ==.
=== checks type too, it could be reason why it doesn't work.
if your array is $companies then
function getCompany($search_id, $companies) {
foreach($company in $companies) {
if ($companies['company_id'] == $search_id) {
return $company;
}
}
return false;
}
$companies = [...];
$search = 17063649000;
if ($company = getCompany($search, $companies) ) {
// do something with $company
} else {
// not found
}
$champions array =
Array (
[0] => Shen
[1] => Graves
[2] => Lux
[3] => Tristana
[4] => Janna
[5] => Lissandra
[6] => RekSai
[7] => Anivia
[8] => Lucian
[9] => Alistar )
This array has always 10 values.
$fbps array =
Array (
[0] => RekSai
[1] => Alistar
[2] => Lucian )
This array has always 1-5 values.
What i want to make
Array (
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 1
[7] => 0
[8] => 1
[9] => 1 )
My english is bad to explain this, i hope arrays are enough to tell. Sorry for bad title and explanation.
Edit: Ill try to explain it more. For example Shen's key is 0 in first array. $fbps array doesnt have a value named "Shen" so in third array 0 => 0. Lucian's key is 8 in first array. fbps have a value named Lucian. So third arrays 8th key has value "1"
$cArr = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Anivia','Lucian');
foreach ($cArr as $key=>$value) {
if(array_search($value, $fbps) !== false) {
$cArr[$key] = 1;
} else {
$cArr[$key] = 0;
}
}
var_dump($cArr);
Or a more compact version:
$cArr = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Anivia','Lucian');
foreach ($cArr as $key=>$value) {
$cArr[$key] = (array_search($value, $fbps) !== false) ? 1 : 0;
}
var_dump($cArr);
EDIT:
added in the !== false conditional as matches found in position 0 of the $fbps array incorrectly evaluated to false because 0 also = false in PHP land...
EDIT 2:
This function has O(N) complexity, meaning it'll grow linearly and in direct proportion to the size of the input data set.
Does the resulting array just have a value of 1 for every element of $fbps that appears in $champions? If so, something like this should do it;
$champions = ['Shen', 'Graves', 'Alister', '...'];
$fbps = ['Shen', 'Alister', '...'];
$result = array_map(function($value) use ($fbps) {
return (int)in_array($value, $fbps);
}, $champions);
I know you've already accepted an answer but here is the most efficient solution:
<?php
// Your arrays
$champions = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Alistar','Lucian');
// New array which will store the difference
$champ_compare = array();
// Flip the array so that it is associative and uses the names as keys
// http://php.net/manual/en/function.array-flip.php
$fbps = array_flip($fbps);
// Loop all champions and use $v as reference
foreach($champions as &$v)
{
// Check for the existent of $v in the associative $fbps array
// This is leaps and bounds faster than using in_array()
// Especially if you are running this many times with an unknown number of array elements
$champ_compare[] = (int)isset($fbps[$v]);
}
unset($v);
// Flip it back if you need to
$fbps = array_flip($fbps);
print_r($champ_compare);
If you just want the most compact code and do not care about performance then you can try this:
<?php
// Your arrays
$champions = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Alistar','Lucian');
// New array which will store the difference
$champ_compare = array();
// Loop all champions and use $v as reference
foreach($champions as &$v)
{
// Check if the current champion exists in $fbps
$champ_compare[] = (int)in_array($v, $fbps);
}
unset($v);
print_r($champ_compare);
Not as detailed as Garry's answer, but is based on your existing arrays.
$res = array()
foreach($champions as $key => $val) {
$res[$key] = (in_array($val, $fbps)) ? 1 : 0;
}
var_dump($res)
Edit: I've switched the array_key_exists to in_array.
<?php
$champions = array('Shen', 'Graves', 'Lux', 'Tristana', 'Janna', 'Lissandra', 'RekSai', 'Anivia', 'Lucian', 'Alistar');
$fbps = array('RekSai', 'Alistar', 'Lucian');
$res = array();
foreach($champions as $key => $val) {
$res[$key] = (in_array($val, $fbps)) ? 1 : 0;
}
var_dump($res);
I would like to find a given value and return the key, Ive tried many ways of solving this but none work.
I spent many hours testing diffrent solutions but no luck so far, yet this is such a simple task.
Here are some functions that I have tried but none return the correct key: (in this case should be 0)
This returns nothing:
$mapkey = $data['srv']['map_image'];
$ikey = array_search($mapkey, $data['srv']['maps']);
if ($ikey !== FALSE) {
// Match made.
}
I get '3' when it should be '0', from this one:
foreach ($data['srv']['maps'] as $key => $value) {
$mapkey = ($data['srv']['map_image']);
if ($value === $mapkey && $data['srv']['maps'][$key]['map_image'] === $mapkey) {
return $key;
}
}
I get nothing from this and should be '0':
$mapkey = $data['srv']['map_image'];
foreach ($data['srv']['maps'] as $key => $val) {
if ($val === $mapkey) {
return $key;
}
}
This one completely crashes the web page:
function recursive_array_search($mapkey,$data) {
foreach($data['srv']['maps'] as $key=>$val) {
$mapkey = $data['srv']['map_image'];
$imagekey=$key;
if($mapkey===$val OR (is_array($val) && recursive_array_search($mapkey,$val) !== false)) {
return $imagekey;
}
}
return false;
}
Example of the $data array:
Array
(
[srv] => Array
(
[map_name] => map 1
[map_image] => MP_001
[maps] => Array
(
[0] => Array
(
[map_name] => map 1
[map_image] => mp_001
)
[1] => Array
(
[map_name] => map 2
[map_image] => mp_017
)
[2] => Array
(
[map_name] => map 3
[map_image] => mp_014
)
[3] => Array
(
[map_name] => map 4
[map_image] => mp_007
)
)
)
)
Ok I have come up with a solution.
foreach ($data['srv']['maps'] as $key => $value) {
$mapkey = strtolower($data['srv']['map_image']);
if ($mapkey == $data['srv']['maps'][$key]['map_image']) {
$imgkey = $key;
}
}
echo '<pre>';
print_r($imgkey);
echo '</pre>';
Returns '0'
The problem I had was where the code was being placed and the fact I couldn't have $key returned as it broke the rest of the code.
In the first one, you are searching directly inside the $data['srv']['maps'] which contains keys like 0 , 1 . But you have to search inside all the 0 , 1s so it fails.
In second one, if you remove the first condition it shall work. Bcoz in first condition you are comparing a value with an array ($value) is an array.
The above mistake you are doing in third also.
Fourth is too complicated. Best thing is thata you remove the first condition from second one.
Update: As per your update, for comparison they shall be in same case ;-)
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
I'm fetching some JSON from flickrs API. My problem is that the exif data is in different order depending on the camera. So I can't hard-code an array number to get, for instance, the camera model below. Does PHP have any built in methods to search through associative array values and return the matching arrays? In my example below I would like to search for the [label] => Model and get [_content] => NIKON D5100.
Please let me know if you want me to elaborate.
print_r($exif['photo']['exif']);
Result:
Array
(
[0] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Make
[label] => Make
[raw] => Array
(
[_content] => NIKON CORPORATION
)
)
[1] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Model
[label] => Model
[raw] => Array
(
[_content] => NIKON D5100
)
)
[2] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => XResolution
[label] => X-Resolution
[raw] => Array
(
[_content] => 240
)
[clean] => Array
(
[_content] => 240 dpi
)
)
$key = array_search('model', array_column($data, 'label'));
In more recent versions of PHP, specifically PHP 5 >= 5.5.0, the function above will work.
To my knowledge there is no such function. There is array_search, but it doesn't quite do what you want.
I think the easiest way would be to write a loop yourself.
function search_exif($exif, $field)
{
foreach ($exif as $data)
{
if ($data['label'] == $field)
return $data['raw']['_content'];
}
}
$camera = search_exif($exif['photo']['exif'], 'model');
$key = array_search('Model', array_map(function($data) {return $data['label'];}, $exif))
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. In this case we are returning the label.
The array_search() function search an array for a value and returns the key. (in this case we are searching the returned array from array_map for the label value 'Model')
This would be fairly trivial to implement:
$model = '';
foreach ($exif['photo']['exif'] as $data) {
if ($data['label'] == 'Model') {
$model = $data['raw']['_content'];
break;
}
}
foreach($exif['photo']['exif'] as $row) {
foreach ($row as $k => $v) {
if ($k == "label" AND $v == "Model")
$needle[] = $row["raw"];
}
}
print_r($needle);
The following function, searches in an associative array both for string values and values inside other arrays. For example , given the following array
$array= [ "one" => ["a","b"],
"two" => "c" ];
the following function can find both a,b and c as well
function search_assoc($value, $array){
$result = false;
foreach ( $array as $el){
if (!is_array($el)){
$result = $result||($el==$value);
}
else if (in_array($value,$el))
$result= $result||true;
else $result= $result||false;
}
return $result;
}
$data = [
["name"=>"mostafa","email"=>"mostafa#gmail.com"],
["name"=>"ali","email"=>"ali#gmail.com"],
["name"=>"nader","email"=>"nader#gmail.com"]];
chekFromItem($data,"ali");
function chekFromItem($items,$keyToSearch)
{
$check = false;
foreach($items as $item)
{
foreach($item as $key)
{
if($key == $keyToSearch)
{
$check = true;
}
}
if($check == true)
{break;}
}
return $check;}
As far as I know , PHP does not have in built-in search function for multidimensional array. It has only for indexed and associative array. Therefore you have to write your own search function!!