Compare an array based on previous value of the array - php

I have an array that looks like this:
Array (
[0] => Array (
[START] => COI-COK
[RETURN] => CAI - DEL
)
[1] => Array (
[START] => COK - AMM
[RETURN] => CAI - DEL
)
)
I want to check if both 'start' and 'end' values of previous and current array are same or not. If not then, print some value. How can I do it?
This is my attempt:
foreach($data as $datas)
{
$old_start = $datas['START'];
$old_return = $datas['RETURN'];
...
if( ($old_start == $datas['START']) && ($old_return == $datas['RETURN']))
{
}
else
{
}
}
But it didn't work because all the time old_start value will be equal to $datas['START'].
print_r($data) shows this output:
Array (
[0] => Array (
[Sl] => 2
[TRAVELDAY] => 2015-11-11
[RETURNDAY] => 2015-11-27
[START] => COI-COK
[RETURN] => CAI - DEL
)
[1] => Array (
[Sl] => 1
[TRAVELDAY] => 2015-11-11
[RETURNDAY] => 2015-11-27
[START] => COK - AMM
[RETURN] => CAI - DEL
)
)

You have to put the assignment after the comparison, not before:
$old_start = '';
$old_return = '';
foreach($data as $datas)
{
//....
if($old_start=='' || $old_start == $datas['START'] && $old_return == $datas['RETURN'])
{
//....
}
else
{
//code to be executed
}
$old_start = $datas['START'];
$old_return = $datas['RETURN'];
}

Try like this..
$old_start = "";
$old_return = "";
foreach($data as $datas)
{
if( ($old_start == $datas['START']) && ($old_return == $datas['RETURN']))
{
//true code to be executed
}
else
{
//false code to be executed
}
$old_start = $datas['START'];
$old_return = $datas['RETURN'];
}

foreach($data as $sample) {
if (!isset($temp)) {
$temp = $sample;
} else {
if ($temp['START']==$sample['START'] && $temp['RETURN']==$sample['RETURN']) {
; //WHATEVER EQUAL
} else {
; //WHATEVER NOT EQUAL
}
$temp = $sample;
}
}

$array = Array ( 0 => Array ( "START" => "COI-COK", "RETURN" => "CAI - DEL"), 1 => Array ( "START" => "COK - AMM","RETURN" => "CAI - DEL" ),2=> Array ( "START" => "COK - AMM","RETURN" => "CAI - DEL" ) );
$old_start = "";
$old_return = "";
foreach($array as $ak=>$av){
if(empty($old_start)){
$old_start = $av['START'];
$old_return = $av['RETURN'];
}else{
if($old_start == $av['START'] && $old_return == $av['RETURN']){
echo "SAME\n";
}else{
echo "Varies\n";
}
$old_start = $av['START'];
$old_return = $av['RETURN'];
}
}
//Output
Varies //key 1 will not match with key 0 value
Same // key 2 will not match with key 1 value
Hope this clears your logic, add as many array value you want , I modified your array from 2 to 3 to show the difference. This will compare n with n+1 and show the result.

Related

array difference returning edited values

The following code checks the first array(parameter1) aginst the second array(parameter2) and returns an array that tells which elements were modified.
$array_data = array(
"studDetails" => array(
"studDet" => array(
"studClass" => "V",
),
),
"email" => "kavya#opspl.com",
"systemNames" => array("EMR"),
);
$array_edited = $array_data;
//EDITING
$array_edited['email'] = "kam";
$array_edited['studDetails']['studDet']['studClass'] = "VV";
echo "<pre>";
print_r(array_diff_assoc2_deep($array_edited, $array_data));
function array_diff_assoc2_deep($array_edited, $array_data)
{
$difference = array();
foreach ($array_edited as $row => $value) {
if (!isset($array_data[$row]) && !empty($value)) {
$difference['added'][$row] = $value;
} else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
$difference[$row] = array_diff_assoc2_deep($array_edited[$row], $array_data[$row]);
} else if ((string)$value != (string)$array_data[$row]) {
$difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
}
}
$difference = array_filter($difference);
return $difference;
}
OUTPUT:
Array (
[studDetails] => Array (
[studDet] => Array (
[edited] => Array (
[studClass] => Array (
[old] => V
[new] => VV
)
)
)
)
[edited] => Array (
[email] => Array (
[old] => kavya#opspl.com
[new] => kam
)
)
)
I want the output to be in a single edited key no matter how many internal arrays are there.
DESIRED OUTPUT:
Array (
[edited] => Array (
[email] => Array (
[old] => kavya#opspl.com
[new] => kam
)
[studClass] => Array (
[old] => V
[new] => VV
)
)
)
The reason this happens is the recursive call:
$difference[$row] = array_diff_assoc2_deep($array_edited[$row], $array_data[$row]);
With this line, you put each recursive comparison result into a separate key.
If you don't do this but keep the resulting array flat, you'll get what you want:
function array_diff_assoc2_deep($array_edited, $array_data, $difference = array())
{
foreach ($array_edited as $row => $value) {
if (!isset($array_data[$row]) && !empty($value)) {
$difference['added'][$row] = $value;
} else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
$difference = array_diff_assoc2_deep($array_edited[$row], $array_data[$row], $difference);
} else if ((string)$value != (string)$array_data[$row]) {
$difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
}
}
$difference = array_filter($difference);
return $difference;
}
Three lines have changed:
function array_diff_assoc2_deep($array_edited, $array_data, $difference = array())
//{
## REMOVED: $difference = array();
// foreach ($array_edited as $row => $value) {
// if (!isset($array_data[$row]) && !empty($value)) {
// $difference['added'][$row] = $value;
// } else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
$difference = array_diff_assoc2_deep($array_edited[$row], $array_data[$row], $difference);
// } else if ((string)$value != (string)$array_data[$row]) {
// $difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
// }
//
// }
// $difference = array_filter($difference);
// return $difference;
//}
You can see the output here.

An idea of algorithm to find all possibilities by excluding members of an array ?

I will use this function in this loop :
while ($nbrDocument < 12 && $nbrTags > 0)
{
$tmpDocuments = $this
->get('fos_elastica.manager')
->getRepository('AppBundle:Document')
->findFromTag();
$tagPossibilities = $this->generateTagPossibilities($userTags, $nbrTags);
foreach ($tmpDocuments as $document)
{
$present = true;
foreach ($tagPossibilities as $tags)
{
foreach ($tags as $tag)
{
if (!in_array($tag, $document->getTag()))
{
$present = false;
break;
}
}
if ($present) {
break;
}
}
$nbrDocument ++;
array_push($documents, $$document);
}
$nbrTags--;
}
And I need to create the method generateTagPossibilities.
The first parameter contains an array of string data, and the second is the size
of the possibilities I need to have.
For exemple, if I have [1][2][3][4] in my array and $nbrTag = 4, this function should return [1][2][3][4], if $nbrTag = 3, it should return [[1][2][3]] [[1][3][4]] [[2][3][4]] ...
Got any idea of how I can do that ?
You can use the following functions :
function array_hash($a)
{
$s = '';
foreach($a as $v)
{
$s.=$v.'-';
}
return hash('sha256',$s);
}
function removeOne($setList)
{
$returnSetList = array();
$hashList = array();
foreach($setList as $set)
{
foreach($set as $k=>$v)
{
$tmpSet = $set;
unset($tmpSet[$k]);
$hash = array_hash($tmpSet);
if(!in_array($hash, $hashList))
{
$returnSetList[] = $tmpSet;
$hashList[] = $hash;
}
}
}
return $returnSetList;
}
function generateTagPossibilities($userTags, $nbrTags)
{
$aUserTags = array($userTags);
$cUserTags = count($userTags);
if($nbrTags==$cUserTags)
return $aUserTags;
for($i=0; $i<($cUserTags-$nbrTags); $i++)
$aUserTags = removeOne($aUserTags);
return $aUserTags;
}
// Example !
$a = array(1,2,3,4);
print_r(generateTagPossibilities($a,2));
/*
Array
(
[0] => Array
(
[2] => 3
[3] => 4
)
[1] => Array
(
[1] => 2
[3] => 4
)
[2] => Array
(
[1] => 2
[2] => 3
)
[3] => Array
(
[0] => 1
[3] => 4
)
[4] => Array
(
[0] => 1
[2] => 3
)
[5] => Array
(
[0] => 1
[1] => 2
)
)
*/

Edit an array with new values in PHP

I have this array:
Array
(
[datas] => Array
(
[General] => Array
(
[0] => Array
(
[id] => logo
[size] => 10
)
)
[Rooms] => Array
(
[0] => Array
(
[id] => room_1
[size] => 8
)
[1] => Array
(
[id] => room_2
[size] => 8
)
[2] => Array
(
[id] => room_3
[size] => 8
)
)
)
)
I need to update it when I receive some info like this:
$key = 'room_3';
$toChange = '9';
So in my array, I want to change the size of room_3.
I will always edit the same element (i.e. size).
What I tried:
// Function to communicate with the array
getDatas($array, 'room_3', '9');
function getDatas($datas, $got, $to_find) {
foreach ($datas as $d) {
if (array_search($got, $d)) {
if (in_array($to_find, array_keys($d))) {
return trim($d[$to_find]);
}
}
}
}
But it does not work...
Could you please help me ?
Thanks.
function getDatas($datas, $got, $to_find) {
foreach($datas['datas'] as $key => $rows) {
foreach($rows as $number => $row) {
if($row['id'] == $got) {
// u can return new value
return $row['size'];
// or you can change it and return update array
$datas['dates'][$key][$number]['size'] = $to_find; // it should be sth like $new value
return $datas;
}
}
}
}
function changeRoomSize (&$datas, $roomID, $newSize ){
//assuming that you have provided valid data in $datas array
foreach($datas['datas']['Rooms'] as &$room){
if($room['id'] == $roomID){
$room['size'] = $newSize;
break;//you can add break to stop looping after the room size is changed
}
}
}
//--- > define here your array with data
//and then call this function
changeRoomSize($data,"room_3",9);
//print the results
var_dump($data);
It's a 3-dimensional array, if you want to change the value, do like this:
$key = 'room_3';
$toChange = '9';
$array['datas'] = getRooms($array['datas'], $key, $toChange);
function getRooms($rooms, $key, $toChange) {
foreach($rooms as $k1=>$v1) foreach ($v1 as $k2=>$v2) {
if ($v2['id'] == $key)) {
$rooms[$k1][$k2]['size'] = $toChange;
}
}
return $rooms;
}
print_r($array);

How to get the value from serialized array by using preg_match in php

I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);

How to search exits value in 2D array

I want to check value in array if exits then show "Exits" otherwise show "Not in Array"..
1).
I create a array=>
$browse['pro_id'] = $id;
$browse['pro_name'] = $mobile_details[0]['pro_name'];
$browse['pro_brand'] = $mobile_details[0]['pro_brand'];
$browse['pro_price_own'] = $mobile_details[0]['pro_price_own'];
$mob_arr = $browse;
print_r($browse);
//This print array like this..
Array
(
[pro_id] => mob810013034
[pro_name] => Galaxy Y S5360
[pro_brand] => Samsung
[pro_price_own] => 6291
)
2). After this 2 time . i am pusing array in above given array=>
array_push($mob_arr,$browse);
print_r($mob_arr);
//This print array like this...
Array
(
[pro_id] => mob810013034
[pro_name] => Galaxy Y S5360
[pro_brand] => Samsung
[pro_price_own] => 6291
[0] => Array
(
[pro_id] => mobka10013042
[pro_name] => A 1
[pro_brand] => Karbonn
[pro_price_own] => 6000
)
)
I want to check if [pro_id]=mobka10013042 in whole array then continue; else puch array again in $mob_arr
array_push($mob_arr,$browse);
I use in_array but its not working for this...
Please Give me suggestion .....
Try to create a structure like this:
$myarr = Array
(
[0] => Array
(
[pro_id] => mob810013034
[pro_name] => Galaxy Y S5360
[pro_brand] => Samsung
[pro_price_own] => 6291
)
[1] => Array
(
[pro_id] => mobka10013042
[pro_name] => A 1
[pro_brand] => Karbonn
[pro_price_own] => 6000
)
)
Then use pop to retrieve whose values:
$mob_arr = array();
while(!empty($myarr))
{
$temp = array_pop($myarr);
if($temp['pro_id']!='mobka10013042'){
array_push($mob_arr,$temp);
}
}
if(empty($mob_arr)){
//actions when mob_arr variable is empty
} else {
//if not
}
Not sure what the approach is.But this might help to get things started.
$mob_arr = array();
$browse['pro_id'] = 'mob810013034';
$browse['pro_name'] = 'Galaxy Y S5360';
$browse['pro_brand'] = 'Samsung';
$browse['pro_price_own'] = '6291';
array_push($mob_arr,$browse);
$browse['pro_id'] = 'mobka10013042';
$browse['pro_name'] = 'A 1';
$browse['pro_brand'] = 'Karbonn';
$browse['pro_price_own'] = '6000';
array_push($mob_arr,$browse);
if(checkId($mob_arr, 'pro_id', 'mobka10013042')) {
print 'found the value...';
} else {
print 'no can not find the value...';
}
function checkId($arr, $k, $v) {
foreach($arr as $browse) {
if($browse[$k] == $v) {
return true;
}
}
return false;
}
$i=0;
foreach($mob_arr as $row )
{
if(is_array($row))
{
if(in_array('mobka10013042',$row))
{
$i=1;
}
}
}
if($i==1)
{
continue
}
else
{
// push another array
}

Categories