I have two different arrays (say) array1 and array2. I want to check whether a value in array2 exists in array1.
Array1
(
[0] => Array
(
[id] => 7
[title] => Course1
)
[1] => Array
(
[id] => 8
[title] => course2
)
[2] => Array
(
[id] => 9
[title] => course3
)
)
Array2
(
[0] => 7
[1] => 8
)
I used:
foreach ($array2 as $id) {
$found = current(array_filter($array1, function($item) {
return isset($item['id']) && ($id == $item['id']);
}));
print_r($found);
}
When I run this code it give the following error:
Undefined variable: id
The reason for your error is that you are trying to use a variable within your anonymous function that is not available to it. Have a read of the relevant PHP documentation (esp. Example #3) to make sure you are clear on what I'm talking about.
In brief, your variable $id is declared in the parent scope of your closure (or anonymous function). In order for it to be available within your closure you must make it available via the use statement.
If you change the key line of your code to be:
$found = current(array_filter($array1, function($item) use ($id) {
your program should work as expected.
Here is simple code as per your question :
foreach($array2 as $id){
return in_array($id, array_column($array1, 'id'));
}
Make sure this is a useful to you.
Related
I have a huge array in which keys are also not constant in most of the cases, but there are 3 keys that always constant (#name,#default_value,#value) and #default_value and #value is different i want to get these kind of sub arrays in 1 simple array , for this purpose i am using recursion in whole array and checking out if these 3 keys are present there i can print these values inside recursion easily but I am not able to get those values in return. So that i can precess them further.
$form=array();
$form['field_one']['#name']="field_one";
$form['field_one']['#default_value']="old";
$form['field_one']['#value']="new";
$form['field_two']['#name']="field_two";
$form['field_two']['#default_value']="old";
$form['field_two']['#value']="new";
$form['field_three']['#name']="field_three";
$form['field_three']['#default_value']="old";
$form['field_three']['#value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#name']="field_four";
$form['thiscouldbeanotherarray']['idk']['field_four']['#default_value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#value']="new";
$arr_get = get_updatedvalues($form,array());
var_dump($arr_get);
function get_updatedvalues($form,$fields) {
if (!is_array($form)) {
return;
}
foreach($form as $k => $value) {
if(str_replace('#','',$k) =='default_value' && ($form['#default_value'] != $form['#value'] ) ){
$fields['field'][$form['#name']] = array("name" => $form['#name'],"old_value" =>$form['#default_value'],"new_value" =>$form['#value']);
var_dump($fields);
}
get_updatedvalues($value,$fields);
}
return $fields;
}
If you run this code it will give you $arr_get > array (size=0), there i need all three values
If I understand correctly, you need to pass fields as a reference in order to change it:
function get_updatedvalues($form, &$fields) {
To do that, however, you'll need to change your initial call so that you have a variable to pass as the reference:
$array = [];
$arr_get = get_updatedvalues($form,$array);
Running this I get:
Array
(
[field] => Array
(
[field_one] => Array
(
[name] => field_one
[old_value] => old
[new_value] => new
)
[field_two] => Array
(
[name] => field_two
[old_value] => old
[new_value] => new
)
[field_four] => Array
(
[name] => field_four
[old_value] => old
[new_value] => new
)
)
)
This question already has answers here:
How can I remove duplicates in an object array in PHP?
(2 answers)
Closed 8 years ago.
When I print $online_performers variable I want to get a unique value for id 2. Do I need to convert them in standard array first or is that possible without it? (remove all duplicates).Please check my new code for this.
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[2] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[3] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
to
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
PHP has a function called array_filter() for that purpose:
$filtered = array_filter($array, function($item) {
static $counts = array();
if(isset($counts[$item->id])) {
return false;
}
$counts[$item->id] = true;
return true;
});
Note the usage of the static keyword. If used inside a function, it means that a variable will get initialized just once when the function is called for the first time. This gives the possibility to preserve the lookup table $counts across multiple function calls.
In comments you told, that you also search for a way to remove all items with id X if X appears more than once. You could use the following algorithm, which is using a lookup table $ids to detect elements which's id occur more than ones and removes them (all):
$array = array("put your stdClass objects here");
$ids = array();
$result = array();
foreach($array as $item) {
if(!isset($ids[$item->id])) {
$result[$item->id]= $item;
$ids[$item->id] = true;
} else {
if(isset($result[$item->id])) {
unset($result[$item->id]);
}
}
}
$result = array_values($result);
var_dump($result);
If you don't care about changing your keys you could do this with a simple loop:
$aUniq = array ();
foreach($array as $obj) {
$aUniq[$obj->id] = $obj;
}
print_r($aUniq);
Let's say we have:
$array = [
//items 1,2,3 are same
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
Then duplication depends of what do you mean. For instance, if that's about: two items with same id are treated as duplicates, then:
$field = 'id';
$result = array_values(
array_reduce($array, function($c, $x) use ($field)
{
$c[$x->$field] = $x;
return $c;
}, [])
);
However, if that's about all fields, which should match, then it's a different thing:
$array = [
//1 and 3 are same, 2 and 3 are not:
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
You'll need to identify somehow your value row. Easiest way is to do serialize()
$result = array_values(
array_reduce($array, function($c, $x)
{
$c[serialize($x)] = $x;
return $c;
}, [])
);
But that may be slow since you'll serialize entire object structure (so you'll not see performance impact on small objects, but for complex structures and large amount of them it's sounds badly)
Also, if you don't care about keys in resulting array, you may omit array_values() call, since it serves only purpose of making keys numeric consecutive.
I have an array with the following values
- Array ( [id] => 3 [parent_id] => 2 [name] => Fitness )
- Array ( [id] => 4 [parent_id] => 3 [name] => Why do it)
- Array ( [id] => 5 [parent_id] => 3 [name] => Nutrition)
Id like to query it along the lines of
array_search([parent_id]='3', $array)
and return a list of matching elements. (In this instance it would be id's 4 & 5). I'm not sure if array_search() is the right way to go about this. May attempts are failing at moment.
<?php
function mySearchArr($key, $value, $myBigArr) {
$searchArr = array();
foreach($myBigArr as $smallArr)
if($smallArr[$key] == $value)
$searchArr[] = $smallArr;
return $searchArr
}
$matches = mySearchArr('parent_id', 3, $array);
?>
You could use array_filter with a custom callback
$lookup_id = 3;
$results = array_filter($your_array, function($arr) use ($lookup_id) {
return $your_array['parent_id'] == $lookup_id;
});
This code requires i believe >=PHP5.3, if you have an older version, you will have to implement the callback using either an actual defined function (normal php function), or using create_function
I've got an multi-dimensional array at the moment and want to remove the second-level of arrays and have the value of that second level as the new index value on the parent array. My current array is:
Array ( [0] => Array ( [connectee] => 1 ) [1] => Array ( [connectee] => 6 ) )
And want from that:
Array ( [0] => 1, [1] => 6 )
I was poking around the usort function but couldn't get it to work (where $current_connections is my array as above:
function cmp($a, $b) {
return strcmp($a["connectee"], $b["connectee"]);
}
$current_connections = usort($current_connections, "cmp");
The key doesn't need to be maintained (should be destroyed in the process).
foreach ($array as &$value) {
$value = $value['connectee'];
}
Note: Please note that the question statement is very confusing and contradicting, but this answer is based upon your statement for expected output
Array ( [0] => 1, [1] => 6 )
You could do
<?php
$values=array();
$values[0]=array("connectee"=>1);
$values[1]=array("connectee"=>6);
foreach($values as $index=>$value)
{
$values[$index]=$value["connectee"];
}
print_r($values);
?>
I've never really used PHP arrays before as I've just used a database in the past so I'm broadening my horizons a little. Basically I have a simple nested array where each element has a 'name' and some other values. I'm trying to search through the array, which is part of an object. I've looked through a number of previous questions on here and can't get it working, although in the other cases there haven't been objects involved. I've been trying to use a 'needle/haystack' type example but haven't got it working yet.
So in my People class we have among other things:
public $peopleArray; // this is the array and will be protected once working
// and this is the example search function im trying to modify
public function findPerson($needle, $haystack)
{
foreach($haystack as $key=>$value)
{
if(is_array($value) && array_search($needle, $value) !== false)
{
return $key;
}
}
return 'false';
}
And then to call this I currently have:
$searchResult = $People->findPerson('Bob',$people->peopleArray,'name');
I'm not sure if I'm just confusing myself with what the $needle and $value - I need to pass the name value in the search function, so I did have $value in the function arguments, but this still returned nothing. Also I'm not 100% on whether '$key=>$value' needs modifying as $key is undefined.
Thanks in advance for any help.
Addition - print_r of the array:
Array ( [0] => Person Object ( [id:protected] => 1 [name] => Bob [gender] => m )
[1] => Person Object ( [id:protected] => 2 [name] => Denise [gender] => f )
[2] => Person Object ( [id:protected] => 3 [name] => Madge [gender] => f ) )
Ok this would be a lot easier if you had to post an example array, but I'm going to give this question a shot.
To me it seems you are looping through a 2D array (nested array).
I would loop through multidimensional arrays like such:
for($array as $key => $2ndArray){
for($2ndArray as $2ndKey => $value){
if($value == $needle){
return true;
}
}
}
Hope this helps