Search nested multidimensional array - php

I have a function that fills an array:
foreach ($request->get('ids') as $id) {
$pdfArray['other']++; // Yes this is initialized
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}
What I want to do
On each loop, I want to check if the array (so far) already has a desc entry equal to the current $schedule->getDescription() AND the same date as $schedule->getStart()->format('d.m.Y') (actually more, but let's keep it simple)
What I tried
public function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && $this->recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Source
I use it like that:
if ($this->recursive_array_search($schedule->getDescription(), $pdfArray['rows']) &&
$this->recursive_array_search($schedule->getStart()->format('d.m.Y'), $pdfArray['rows'])){
$pdfArray['ma'][$schedule->getId()]++;
}
but this is true when ANY of the start or desc are SOMEWHERE in the current array.
How would I check if desc is found and start is in the SAME $i level?
EDIT for example
Let's say I have 10 $ids to loop through. After 2 loops, the $pdfArray looks like this:
Array
(
[other] => 2
[rows] => Array
(
[0] => Array
(
[id] => 1
[date] => 13.07.2016
[dateSort] => 2016-07-13 08:00
[from] => 08:00
[to] => 09:00
[desc] => TEST
)
[1] => Array
(
[id] => 2
[date] => 12.07.2016
[dateSort] => 2016-07-12 08:00
[from] => 08:00
[to] => 09:00
[desc] => TEST
)
)
)
The next iteration has the following:
$schedule->getStart()->format('d.m.Y') => 12.07.2016
$schedule->getDescription() => TEST
So I want to have the info that the combination already exists in the array.
BUT
$schedule->getStart()->format('d.m.Y') => 12.07.2016
$schedule->getDescription() => TEST2
should NOT return true upon checking of it exists.

To test for a "duplicate" you can use this function:
function testPresence($pdfArray, $desc, $date) {
foreach ($pdfArray["rows"] as $row) {
if ($row["desc"] == $desc && $row["date"] == $date) return true;
}
}
Example use:
echo testPresence($pdfArray, "TEST2", "12.07.2016") ? "Found" : "Not found"; // Not found
echo testPresence($pdfArray, "TEST", "12.07.2016") ? "Found" : "Not found"; // Found
In your original loop, you can use it as follows:
foreach ($request->get('ids') as $id) {
if (testPresence($pdfArray, $schedule->getDescription(),
$schedule->getStart()->format('d.m.Y')) {
// We have a duplicate. Maybe skip this entry?:
continue;
}
$pdfArray['other']++;
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}

try this at your validation function
public function array_search($needle1, $needle2 ,$haystack) {
foreach($haystack as $singleArray){
if (in_array($needle1, $singleArray) && in_array($needle2, $singleArray))
return true;
else
continue;
}
return false;
}
and invoke your recursive_array_search like this
if ($this->array_search($schedule->getStart(), $schedule->getDescription(), $pdfArray['rows'])
continue;//Or any other kind of logic you want. At this place you know that description and date staet exist in at your array level
$pdfArray['other']++; // Yes this is initialized
$pdfArray['rows'][$i]['id'] = $schedule->getId();
$pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
$pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
$pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
$pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
$pdfArray['rows'][$i]['desc'] = $schedule->getDescription();

Function version:
/**
* Find matches for $item into pdfArray.
* Returns an index array, possibly empty if no matches.
* #param $item item to find
* #param $rows rows where to search
*/
function findPdfArrayMatches(array $item, array $rows) {
return array_keys(
array_filter(
$rows,
function ($entry) use ($item) {
// These are the matching criteria. More than one row may match.
return $entry['desc'] == $item['desc']
&& $entry['date'] == $item['date']
;
}
)
);
}
You could do like this, in the loop:
$item = [
'id' => $schedule->getId(),
'date' => $schedule->getStart()->format('d.m.Y'),
'dateSort' => $schedule->getStart()->format('Y-m-d H:i'),
'from' => $schedule->getStart()->format('H:i'),
'to' => $schedule->getEnd()->format('H:i'),
'desc' => $schedule->getDescription(),
];
$matches = findPdfArrayMatches($item, $pdfArray['rows']);
if (!empty($matches)) {
...do something with the matches:
foreach ($matches as $match) {
$pdfArray['rows'][$match]['Duplicate'] = true;
}
}
// Add new item
$pdfArray['rows'][$i] = $item;

Related

How to find object in php array and delete it?

Here is print_r output of my array:
Array
(
[0] => stdClass Object
(
[itemId] => 560639000019
[name] => Item no1
[code] => 00001
[qty] => 5
[id] => 2
)
[1] => stdClass Object
(
[itemId] => 470639763471
[name] => Second item
[code] => 76347
[qty] => 9
[id] => 4
)
[2] => stdClass Object
(
[itemId] => 56939399632
[name] => Item no 3
[code] => 39963
[qty] => 6
[id] => 7
)
)
How can I find index of object with [id] => 4 in order to remove it from array?
$found = false;
foreach($values as $key => $value) {
if ($value->id == 4) {
$found = true;
break;
}
}
if ($found) unset($values[$key]);
This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.
foreach($parentObj AS $key=>$element){
if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
echo "Gottcha! The index is - ". $key;
}
}
$parentObj is obviously your root array - the one that holds all the others.
We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.
use array_search:
$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;
$arr = array($a, $b);
$index = array_search($b, $arr);
echo $index;
// prints out 1
try this
foreach($array AS $key=>$object){
if($object['id'] == 4){
$key_in_array = $key;
}
}
// chop it from the original array
array_slice($array, $key_in_array, 1);
Another way to achieve the result is to use array_filter.
$array = array(
(object)array('id' => 5),
(object)array('id' => 4),
(object)array('id' => 3)
);
$array = array_filter($array, function($item) {
return $item->id != 4;
});
print_r($array);
Here's my solution. Given, it is a bit hackish, but it will get the job done.
search(array $items, mixed $id[, &$key]);
Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.
function search($items, $id, &$key = null) {
foreach( $items as $item ) {
if( $item->id == $id ) {
$key = key($item);
return $item;
break;
}
}
return null;
}
Usage
$item = search($items, 4, $key);
unset($items[$key]);
Note: This could be modified to allow a custom key and return multiple items that share the same value.
I've created an example so you can see it in action.
A funny alternative
$getIdUnset = function($id) use ($myArray)
{
foreach($myArray as $key => $obj) {
if ($obj->id == $id) {
return $key;
}
}
return false;
};
if ($unset = $getIdUnset(4)) {
unset($myArray[$unset]);
}
Currently php does not have any supported function for this yet.
So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:
public function indexOf($object, array $elementData) {
$elementCount = count($elementData);
for ($i = 0 ; $i < $elementCount ; $i++){
if ($object == $elementData[$i]) {
return $i;
}
}
return -1;
}
You can save this function as a core function for later.
In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.
array(3) {
[0]=> float(-0.12459619130796)
[1]=> float(-0.64018439966448)
[2]=> float(0)
}
Then use if condition to stop looping
foreach($array as $key => $val){
if($key == 0){ //the key is 0
echo $key; //find the key
echo $val; //get the value
}
}
I know, after so many years this could be a useless answer, but why not?
This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.
if (!function_exists('index_of'))
{
/**
* #param iterable $haystack
* #param callable $callback
* #param mixed|null &$item
* #return false|int|string
*/
function index_of($haystack, $callback, &$item = null)
{
foreach($haystack as $_key => $_item) {
if ($callback($_item, $_key) === true) {
$item = $_item;
return $_key;
}
}
return false;
}
}
foreach( $arr as $k=>&$a) {
if( $a['id'] == 4 )
unset($arr[$k]);
}

PHP: Count the appearance of particular value in array

I am wondering if I could explain this.
I have a multidimensional array , I would like to get the count of particular value appearing in that array
Below I am showing the snippet of array . I am just checking with the profile_type .
So I am trying to display the count of profile_type in the array
EDIT
Sorry I've forgot mention something, not something its the main thing , I need the count of profile_type==p
Array
(
[0] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => p
[birthyear] => 1978
[is_elite] => 0
)
)
[1] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => d
[birthyear] => 1972
[is_elite] => 1
)
)
)
Easy solution with RecursiveArrayIterator, so you don't have to care about the dimensions:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$counter = 0
foreach ($iterator as $key => $value) {
if ($key == 'profile_type' && $value == 'p') {
$counter++;
}
}
echo $counter;
Something like this might work...
$counts = array();
foreach ($array as $key=>$val) {
foreach ($innerArray as $driver=>$arr) {
$counts[] = $arr['profile_type'];
}
}
$solution = array_count_values($counts);
I'd do something like:
$profile = array();
foreach($array as $elem) {
if (isset($elem['Driver']['profile_type'])) {
$profile[$elem['Driver']['profile_type']]++;
} else {
$profile[$elem['Driver']['profile_type']] = 1;
}
}
print_r($profile);
You may also use array_walk($array,"test") and define a function "test" that checks each item of the array for 'type' and calls recursively array_walk($arrayElement,"test") for items of type 'array' , else checks for the condition. If condition satisfies, increment a count.
Hi You can get count of profuke_type==p from a multi dimensiona array
$arr = array();
$arr[0]['Driver']['id'] = 4;
$arr[0]['Driver']['profile_type'] = 'p';
$arr[0]['Driver']['birthyear'] = 1978;
$arr[0]['Driver']['is_elite'] = 0;
$arr[1]['Driver']['id'] = 4;
$arr[1]['Driver']['profile_type'] = 'd';
$arr[1]['Driver']['birthyear'] = 1972;
$arr[1]['Driver']['is_elite'] = 1;
$arr[2]['profile_type'] = 'p';
$result = 0;
get_count($arr, 'profile_type', 'd' , $result);
echo $result;
function get_count($array, $key, $value , &$result){
if(!is_array($array)){
return;
}
if($array[$key] == $value){
$result++;
}
foreach($array AS $arr){
get_count($arr, $key, $value , $result);
}
}
try this..
thanks

PHP find value in multidimensional / nested array

I've trawled the site and the net and have tried various recursive functions etc to no avail, so I'm hoping someone here can point out where I'm going wrong :)
I have an array named $meetingArray with the following values;
Array (
[0] => Array (
[Meet_ID] => 9313
[Meet_Name] => 456136
[Meet_CallInNumber] =>
[Meet_AttendeeCode] =>
[Meet_Password] =>
[Meet_ScheduledDateTime] => 2011-07-18 16:00:00
[Meet_ModeratorCode] =>
[Meet_RequireRegistration] => 0
[Meet_CurrentUsers] => 0
)
[1] => Array (
[Meet_ID] => 9314
[Meet_Name] => 456120
[Meet_CallInNumber] =>
[Meet_AttendeeCode] =>
[Meet_Password] =>
[Meet_ScheduledDateTime] => 2011-07-18 16:00:00
[Meet_ModeratorCode] =>
[Meet_RequireRegistration] => 0
[Meet_CurrentUsers] => 0
)
)
I also have a variable named $meetID.
I want to know if the value in $meetID appears in [Meet_Name] within the array and simply evaluate this true or false.
Any help very much appreciated before I shoot myself :)
function multi_in_array($needle, $haystack, $key) {
foreach ($haystack as $h) {
if (array_key_exists($key, $h) && $h[$key]==$needle) {
return true;
}
}
return false;
}
if (multi_in_array($meetID, $meetingArray, 'Meet_Name')) {
//...
}
I am unsure what you mean by
$meetID appears in [Meet_Name]
but simply substitute the $h[$key]==$needle condition with something that meets your needs.
For single-dimensional arrays you can use array_search(). This can be adapted for multi-dimensional arrays like so:
function array_search_recursive($needle, $haystack, $strict=false, $stack=array()) {
$results = array();
foreach($haystack as $key=>$value) {
if(($strict && $needle === $value) || (!$strict && $needle == $value)) {
$results[] = array_merge($stack, array($key));
}
if(is_array($value) && count($value) != 0) {
$results = array_merge($results, array_search_recursive($needle, $value, $strict, array_merge($stack, array($key))));
}
}
return($results);
}
Write a method something like this:
function valInArr($array, $field, $value) {
foreach ($array as $id => $nestedArray) {
if (strpos($value,$nestedArray[$field])) return $id;
//if ($nestedArray[$field] === $value) return $id; // use this line if you want the values to be identical
}
return false;
}
$meetID = 1234;
$x = valInArr($array, "Meet_Name", $meetID);
if ($x) print_r($array[$x]);
This function will evaluate true if the record is found in the array and also enable you to quickly access the specific nested array matching that ID.

Return true/false on searching multidimensional array

I have the following multidimensional $array:
Array
(
[0] => Array
(
[domain] => example.tld
[type] => 2
)
[1] => Array
(
[domain] => other.tld
[type] => 2
)
[2] => Array
(
[domain] => blaah.tld
[type] => 2
)
)
I simply want to recursively search all the arrays on both key and value, and return true if the key/value was found or false if nothing was found.
Expected output:
search_multi_array($array, 'domain', 'other.tld'); // Will return true
search_multi_array($array, 'type', 'other.tld'); // Will return false
search_multi_array($array, 'domain', 'google.com'); // Will return false
I've figured out a ugly-ugly method to search against the domain against all keys with this function:
function search_multi_array($search_value, $the_array) {
if (is_array($the_array)) {
foreach ($the_array as $key => $value) {
$result = search_multi_array($search_value, $value);
if (is_array($result)) {
return true;
} elseif ($result == true) {
$return[] = $key;
return $return;
}
}
return false;
} else {
if ($search_value == $the_array) {
return true;
}
else
return false;
}
}
Can anyone do better and match both against the key and value in a more elegant way?
If it doesn't go beyond those 2 levels, flipping keys/merging makes life a lot more pleasant:
<?php
$data = array
(
'0' => array
(
'domain' => 'example.tld',
'type' => 2
),
'1' => array
(
'domain' => 'other.tld',
'type' => 2,
),
'2' => array
(
'domain' => 'blaah.tld',
'type' => 2
)
);
$altered = call_user_func_array('array_merge_recursive',$data);
var_dump($altered);
var_dump(in_array('other.tld',$altered['domain']));
var_dump(in_array('other.tld',$altered['type']));
var_dump(in_array('google.com',$altered['domain']));
To go beyond 2nd level, we have to loop once through all the nodes:
$option2 = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $key => $value){
$option2[$key][] = $value;
}
var_dump($option2);
One way is to create a reverse mapping from [domain] => [indices] and from [type] => [indices]. It's probably not going to save you much unless you do lots of searches.
(hint: you probably want to wrap it into a class to prevent inconsistencies in the mappings)
also, anytime you see something like this:
if ($search_value == $the_array) {
return true;
} else {
return false;
}
you can always turn it into:
return $search_value == $the_array;
function search_mutli_array($SearchKey, $SearchValue, $Haystack)
{
$Result = false;
if (is_array($Haystack))
{
foreach ($Haystack as $Key => $Value)
{
if (is_array($Value))
{
if (search_mutli_array($SearchKey, $SearchValue, $Value))
{
$Result = true;
break;
}
}
else if ($SearchKey == $Key && $SearchValue == $Value)
{
$Result = true;
break;
}
}
}
return $Result;
}

Sort an associative array in php with multiple condition

Consider following array
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n')
);
Here I would like to sort with head and membkey. Top element of same membkey element should have 'head=y' and echoed as,
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n')
);
I tried it as follows
function orderbymemberKey( $a, $b ){
if ( $a[membkey] == $b[membkey] )
return 0;
return($a[membkey] < $b[membkey] )? -1 :1;
}
usort( $details, orderbymemberKey );
and it successfully order by membkey.
Any suggestions please.
You're half way there (though you were sorting backwards for membkey based on your example):
function order_by_member_key($a, $b)
{
if ($a['membkey'] == $b['membkey'])
{
// membkey is the same, sort by head
if ($a['head'] == $b['head']) return 0;
return $a['head'] == 'y' ? -1 : 1;
}
// sort the higher membkey first:
return $a['membkey'] < $b['membkey'] ? 1 : -1;
}
usort($details, "order_by_member_key");
Is this array being pulled from a database? Because, if so, you should be able to make use of ORDER BY clauses to clean it up outside of php.
<?php
$membkey = array();
$head = array();
foreach ($details as $key => $row) {
$membkey[$key] = $row['membkey'];
$head[$key] = $row['head'];
}
array_multisort($membkey, SORT_DESC, $head, SORT_DESC, $details);
print_r($details);
Or, an even more generic solution:
function sort_by($array) {
$arguments = func_get_args();
$array = array_pop($arguments);
$variables = array();
foreach ($arguments as $index => $key) {
$variables[] = '$arguments['.$index.']';
if ($index % 2 == 0) {
$arguments[$index] = array();
foreach ($array as $row) $arguments[$index][] = $row[$key];
}
}
// call_user_func_array will not work in this case
eval('array_multisort('.implode(', ', $variables).', $array);');
return $array;
}
print_r(sort_by('membkey', SORT_DESC, 'head', SORT_DESC, $details));
Ugly but someone wrote a function on php.net:
http://php.net/manual/en/function.sort.php
<?php
$array[0]['name'] = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year'] = '1978';
$array[0]['address'] = 'Street 1';
$array[1]['name'] = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year'] = '1990';
$array[1]['address'] = 'Street 2';
$array[2]['name'] = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year'] = '1982';
$array[2]['address'] = 'Street 3';
function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
// sort by ?
foreach ($array as $pos => $val)
$tmp_array[$pos] = $val[$sort_by];
asort($tmp_array);
// display however you want
foreach ($tmp_array as $pos => $val){
$return_array[$pos][$sort_by] = $array[$pos][$sort_by];
$return_array[$pos][$key1] = $array[$pos][$key1];
if (isset($key2)){
$return_array[$pos][$key2] = $array[$pos][$key2];
}
if (isset($key3)){
$return_array[$pos][$key3] = $array[$pos][$key3];
}
if (isset($key4)){
$return_array[$pos][$key4] = $array[$pos][$key4];
}
if (isset($key5)){
$return_array[$pos][$key5] = $array[$pos][$key5];
}
if (isset($key6)){
$return_array[$pos][$key6] = $array[$pos][$key6];
}
}
return $return_array;
}
//usage (only enter the keys you want sorted):
$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);
//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )

Categories