Compare element in array and loop through each php - php

I want to compare a value of data to a list of element which I had retrieved from php array(decoded json).
First,
This is the first array:
Array1
(
[0] => Array
(
[member_id] => 3
[member_card_num] => 2013011192330791
[member_barcode] => 2300067628912
)
[1] => Array
(
[member_id] => 4
[member_card_num] => 2328482492740000
[member_barcode] => 3545637000
)
[2] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
[3] => Array
(
[member_id] => 1
[member_card_num] => 91001310000057698
[member_barcode] => 000057698
)
)
This is the second Array:
Array2
(
[0] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
)
Second,
I had retrieved the (member_barcode) which I required.
Here is the code:
For Array1:
foreach ($decode1 as $d){
$merchant_barcode = $d ['member_barcode'];
echo $merchant_barcode;
}
For Array2:
foreach ($decode2 as $d2){
$user_barcode = $d2 ['member_barcode'];
echo $user_barcode;
}
Then,
I get this output():
For Array1(merchant_barcode):
2300067628912
3545637000
486126
000057698
For Array2(user_barcode):
486126
The question is, I would to check and compare whether the user_barcode in Array2(486126) is exist/match to one of the merchant_barcode in Array1.
This is my code,
but it only compare the user_barcode in Array2 to the last element(000057698) in Array1,
I want it to loop through each n check one by one. How can I do that?
public function actionCompareBarcode($user_barcode, $merchant_barcode){
if(($user_barcode) == ($merchant_barcode)){
echo "barcode exist. ";
}
else{
echo "barcode not exist";
}
}
In this case, the output I get is "barcode not exist", but it should be "barcode exist".
Anyone can help? Appreciate that. Im kinda new to php.

You could use a nested loop like:
foreach ($decode2 as $d2)
{
$user_barcode = $d2 ['member_barcode'];
foreach ($decode1 as $d)
{
$merchant_barcode = $d ['member_barcode'];
if ($merchant_barcode == $user_barcode)
{
echo "Match found!";
}
else
{
echo "No match found!";
}
}
}

<?
$a = array(
array(
'member_id' => 3,
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => 4,
'member_card_num' => '2328482492740000',
'member_barcode' => '3545637000',
),
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
),
array(
'member_id' => 1,
'member_card_num' => '91001310000057698',
'member_barcode' => '000057698',
)
);
$b = array(
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
array_walk($a, function($item) use($b) {
echo ($b['0']['member_barcode'] == $item['member_barcode'] ? "found" : NULL);
});
?>

I'd use array_uintersect() to calculate if those multidimensional arrays have a common element:
<?php
$a = array(
array(
'member_id' => '3',
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$b = array(
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$match = array_uintersect($a, $b, function($valueA, $valueB) {
return strcasecmp($valueA['member_barcode'], $valueB['member_barcode']);
});
print_r($match);

Try calling that method as you are looping through Array1 and comparing the user_barcode to every value

You can compare two array this way too:
$per_arr = array();
$permissions = array()
foreach ($per_arr as $key => $perms) {
if(isset($permissions[$key]['name'])){
echo $per_arr[$key]['name']; //matched data
}else{
echo $per_arr[$key]['name']; //not matched data
}
}

Related

PHP sort array of objects by two properties

I have an array
Array
(
[0] => stdClass Object
(
[tab_option_name_selector] => 2
[fieldtype] => notes
[order] => 12
)
[1] => stdClass Object
(
[tab_option_name_selector] => 2
[fieldtype] => notes
[order] => 8
)
[2] => stdClass Object
(
[tab_option_name_selector] => 1
[order] => 2
[fieldtype] => selectbox
)
[3] => stdClass Object
(
[tab_option_name_selector] => 2
[order] => 3
[fieldtype] => selectbox
)
)
I'm trying to get this usort function to work
function osort(&$array, $props)
{
if(!is_array($props))
$props = array($props => true);
$me = usort($array, function($a, $b) use ($props) {
foreach($props as $prop => $ascending)
{
if($a->$prop != $b->$prop)
{
if($ascending)
return $a->$prop > $b->$prop ? 1 : -1;
else
return $b->$prop > $a->$prop ? 1 : -1;
}
}
return -1; //if all props equal
});
print_r($props);
return ($me);
}
$tab = osort($objectArray, "tab_option_name_selector", "order");
so sorting by the tab then order.
$tab is empty - any ideas what I'm doing wrong?
Why the extra level of indirection and making things more confusing? Why not usort directly with usort($objectArray, "sortObjects"); using a sortObjects($a,$b) function that does what any comparator does: return negative/0/positive numbers based on the input?
If the tabs differ, return their comparison, if they're the same, return the order comparison; done.
$array = array(
(object)array(
'tab_option_name_selector' => 2,
'fieldtype' => 'notes',
'order' => 12
),
(object)array(
'tab_option_name_selector' => 2,
'fieldtype' => 'notes',
'order' => 8
),
(object)array(
'tab_option_name_selector' => 1,
'order' => 2,
'fieldtype' => 'selectbox'
),
(object)array(
'tab_option_name_selector' => 2,
'order' => 3,
'fieldtype' => 'selectbox'
)
);
function compareTabAndOrder($a, $b) {
// compare the tab option value
$diff = $a->tab_option_name_selector - $b->tab_option_name_selector;
// and return it. Unless it's zero, then compare order, instead.
return ($diff !== 0) ? $diff : $a->order - $b->order;
}
usort($array, "compareTabAndOrder");
print_r($array);
Why don't you use array_multisort? http://php.net/manual/de/function.array-multisort.php
$data = //your array
//Create independent arrays
foreach ($data as $row) {
foreach ($row as $key => $value){
${$key}[] = $value;
//Creates $tab_option_name_selector, $fieldtype and $order array
//in order to use them as independent arrays in array_multisort.
}
}
array_multisort($tab_option_name_selector, SORT_ASC, $order, SORT_ASC, $data);
//$data sorted as expected.
echo "<pre>";
print_r($data);
echo "</pre>";
An example for unlimited number of properties:
$data = [
(object)['volume' => '1', 'edition' => '1'],
(object)['volume' => '2', 'edition' => '1'],
(object)['volume' => '3', 'edition' => '10'],
(object)['volume' => '3', 'edition' => '50'],
(object)['volume' => '3', 'edition' => '20'],
(object)['volume' => '4', 'edition' => '3'],
];
// sorting list by properties
$sorting = ['volume' => SORT_DESC, 'edition' => SORT_ASC];
$arrays = [];
foreach ($sorting as $key => $sort) {
$column = array_column($data, $key);
if (!empty($column)) {
$arrays[] = $column;
$arrays[] = $sort;
}
}
if (!empty($arrays)) {
$arrays[] = $data;
if (!array_multisort(...$arrays)) {
var_dump('some error');
die();
}
// get last array, that is the sorted data
$data = ($arrays[array_key_last($arrays)]);
}
Example partially from php.net - array_multisort

How to store session array variable in PHP in a MySQL database?

I am having problem with session array variable
$_SESSION ['roomsInfo_' . $intHId] = $strRTypeArr;
It automatically destroy when land on the other page, by using the <form action=”booking_level.php”>
foreach ( $arrRoomInfo as $arrRoomDetails ) {
// occup details
$AdultNum = ( int ) $arrRoomDetails->AdultNum;
$ChildNum = ( int ) $arrRoomDetails->ChildNum;
// child ages details
$strChAgs = '';
if (property_exists ( $arrRoomDetails, 'ChildAges' )) {
$childAgs = $arrRoomDetails->ChildAges->ChildAge;
$arrChAge = array ();
foreach ( $childAgs as $chAgs ) {
$chAgs = $chAgs->attributes ();
$arrChAge [] = $chAgs ['age'];
}
$strChAgs = implode ( ":", $arrChAge );
}
// set array for all the above details
$strRTypeArr [$rtId] [$i] = array (
'myRoomSq' => $i,
'roomSeq' => $arrRmSeq,
'adults' => $AdultNum,
'child' => $ChildNum,
'childAges' => $strChAgs,
'maxGuests' => $maxGuests,
'maxChild' => $maxChild,
'name' => $rmName,
'HotelRoomTypeId' => $rtId,
'roomId' => $roomId,
'isPublish' => $isPublish,
'Occupancy' => array (
"attributes" => array (
'avrNgtlyRtComm' => $avrNgtlyRtComm,
'avrNightPrice' => $avrNtPr,
'bedding' => $bedding
),
"boardBase" => array (
'bbId' => $arrBrdBsId,
'bbName' => $arrBrdBsName,
'bbPrice' => $arrBrdBsPrice,
'bbPublishPrice' => $arrBrdBspBPrce,
'strBBaseExists' => $strBBaseExists
),
'PriceBreakdown' => $arrDay,
"dblBrDownPrTourico" => $dblBrDownPrTourico,
"dblTtlBrDownPr" => $dblTtlBrDownPr,
'Supplements' => $arrSupp
),
'Discount' => $arrDst,
'cancelPolicy' => $strCnlionHtml,
'arrCanPolicy' => $arrCanPolicy,
'arrChcrCanPolicy' => $arrChcrCanPolicy,
'chcr_cancelPolicy' => $chcrCancellation,
'curncy' => $strCurn
);
$i ++;
}
}
}
}
$_SESSION ['roomsInfo_' . $intHId] = $strRTypeArr;
How can I store in Session Array Variable in a MySQL database ?
Just make sure that you assign the array the way you assign a normal value and then store the array in your database.
$_SESSION['dArray'] = $strRTypeArr;
//for example:
$strRTypeArr[0][0] = array (
'myRoomSq' => 2.5,
'roomSeq' => "test this",
'adults' => true,
'child' => 5,
'childAges' => "test"
);
$strRTypeArr[0][1] = array (
'myRoomSq' => 3.5,
'roomSeq' => "this is another test",
'adults' => false,
'child' => 6,
'childAges' => "test"
);
$_SESSION['dArray'] = $strRTypeArr;
echo "<pre>";
print_r($_SESSION['dArray']);
echo "</pre>";
//Store this $_SESSION['dArray'] in your database
You can also use json_encode($_SESSION['dArray']); to store your array in the database.

How do I reform this array into a differently structured array

I have an array that looks like this:
[0] => Array
(
[name] => typeOfMusic
[value] => this_music_choice
)
[1] => Array
(
[name] => myMusicChoice
[value] => 9
)
[2] => Array
(
[name] => myMusicChoice
[value] => 8
)
I would like to reform this into something with roughly the following structure:
Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)
I have written the following but it doesn't work:
foreach($originalArray as $key => $value) {
if( !empty($return[$value["name"]]) ){
$return[$value["name"]][] = $value["value"];
} else {
$return[$value["name"]] = $value["value"];
}
}
return $return;
I've tried lots of different combinations to try and get this working. My original array could contain several sets of keys that need converting to arrays (i.e. it's not always going to be just "myMusicChoice" that needs converting to an array) ?
I'm getting nowhere with this and would appreciate a little help. Many thanks.
You just need to loop over the data and create a new array with the name/value. If you see a repeat name, then change the value into an array.
Something like this:
$return = array();
foreach($originalArray as $data){
if(!isset($return[$data['name']])){
// This is the first time we've seen this name,
// it's not in $return, so let's add it
$return[$data['name']] = $data['value'];
}
elseif(!is_array($return[$data['name']])){
// We've seen this key before, but it's not already an array
// let's convert it to an array
$return[$data['name']] = array($return[$data['name']], $data['value']);
}
else{
// We've seen this key before, so let's just add to the array
$return[$data['name']][] = $data['value'];
}
}
DEMO: https://eval.in/173852
Here's a clean solution, which uses array_reduce
$a = [
[
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
],
[
'name' => 'myMusicChoice',
'value' => 9
],
[
'name' => 'myMusicChoice',
'value' => 8
]
];
$r = array_reduce($a, function(&$array, $item){
// Has this key been initialized yet?
if (empty($array[$item['name']])) {
$array[$item['name']] = [];
}
$array[$item['name']][] = $item['value'];
return $array;
}, []);
$arr = array(
0 => array(
'name' => 'typeOfMusic',
'value' => 'this_music_choice'
),
1 => array(
'name' => 'myMusicChoice',
'value' => 9
),
2 => array(
'name' => 'myMusicChoice',
'value' => 8
)
);
$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
if ($x == 0) {
$newArr[$row[$$name]] = $row[$$value];
} else {
if (! is_array($newArr[$row[$$name]])) {
$newArr[$row[$$name]] = array();
}
array_push($newArr[$row[$$name]], $row[$$value]);
}
$x++;
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

To print the value of array.under array

I have to print the all the value of the array written value.
[subscriber] => Array
(
[name] => Subscriber
[capabilities] => Array
(
[read] => 1
[level_0] => 1
)
[default] => Array
(
[deft] => Array (
[one] => 2
[two] => 3
)
[deft_one] => Array (
[one] => t
[two] => h
)
)
)
I have to print each value under the array. So i used a recursion function. But i cant the result. Please help me in recursion function.
Sorry, I am trying till now. Actually i have to print the wp-option table value. There are many serialise array. I want to print all the value individually. I mean when i used the code written bellow i got an array.
function option_value_change () {
global $wpdb;
$myrows = $wpdb->get_results( "SELECT *
FROM `wp_options`");
$temp_url = get_option('siteurl');
$site_url = get_site_url();
foreach ($myrows as $rows){
$option = get_option($rows->option_name);
//print_r($option);
get_option_value($option);
}
}
i can get the table. But in an array. Which array have arrays. So i used an function "get_option_value($option)". as written bellow
function get_option_value($option) {
if(!is_object($option) && !is_array($option)){
echo $option;
}
else{
foreach($option as $option_value){
if(!is_array($option_value)){
echo $option_value;
}
else {
get_option_value($option_value);
}
}
}
}
bUt i cant get all the value. its give an error as
Object of class stdClass could not be converted to string.
So how can i print all the values of the array.
You can use RecursiveArrayIterator example :
$data = array(
'subscriber' => array(
'name' => 'Subscriber',
'capabilities' => array(
'read' => 1,
'level_0' => 1,
),
'default' => array(
'deft' => array(
'one' => 2,
'two' => 3,
),
'deft_one' => array(
'one' => 't',
'two' => 'h',
),
),
),
);
echo "<pre>";
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($it as $var)
{
echo $var , PHP_EOL ;
}
Output
Subscriber
1
1
2
3
t
h
I didn't test it but you can get the idea;
function printArr($obj){
if(!is_array($obj)){
echo $obj;
return;
}
else if(is_array($obj)){
foreach ($obj as $key => $value) {
printArr($obj[$key]);
}
}
}

Categories