PHP unpack array - php

I would like to learn a smart way to unpack nested array. For instance, i have an array variable $rma_data['status'] which looks like below;
[status] => Array
(
[0] => Array
(
[created] => 1233062304107
[statusId] => 5
[statusName] => Open
)
[1] => Array
(
[created] => 1233061910603
[statusId] => 2
[statusName] => New
)
[2] => Array
(
[created] => 1233061910603
[statusId] => 1
[statusName] => Created
)
)
I would like to store the Created timestamps and statusId into an variables based on the condition like: if we find out there is "Open" status exist, we will use Open instead of "New" and "Created" . If there is only New and Created, we will use New instead .
Current version of my way to do that:
for($i=0; $i<count($rma_data['status']); $i++)
{
switch($rma_data['status'][$i]['statusId'])
{
case 5:
case 2:
case 3:
}
Any ideas?

For small to medium scale, what you already have looks good.
My only suggestions would be to use additional variables, for example the count and to unroll some of the compact code to be more efficient and readable.
For example:
$total=count($rma_data['status']);
for($i=0; $i<$total; $i++){
$x=$rma_data['status'][$i];
if($x['statusName']=='Open'){ // Use your criteria
$t=$x['created'];
//...Do Work
}
}

If you're really depended on these three specific values of statusName, a more straightforward and readable way to go about it would be to create an indexed array of status types which you can test more easily.
For example:
$rma_statuses = array();
foreach ((array)$rma_data['status'] as $status) :
$rma_statuses[$status['statusName']] = array(
'created'=>$status['created'],
'id'=>$status['statusId']
);
endforeach;
$rma_stauts = $rma_statuses['open'] ?: ($rma_statuses['new'] ?: $rma_statuses['created']);
// Do something with $rma_stauts['created'] and $rma_stauts['id']

I do not quite understand a necessary condition but it can be like this will help:
$searched_status_id = null;
$searched_timestamp = null;
foreach ($rma_data['status'] as $id => $status) {
if ((!$searched_timestamp && !$searchуd_status_id) ||
($status['statusName'] == 'New' || $status['statusName'] == 'Open')) {
$searched_timestamp = $status['created'];
$searched_status_id = $status['statusId'];
}
if ($status['statusName'] == 'Open') {
break;
}
}

if(is_array($rma_data['status'])){
//assuming there are only three values inside it
//case1
$open = ( $rma_data['status'][0]['statusName'] == 'Open' ||
$rma_data['status'][1]['statusName'] == 'Open' ||
$rma_data['status'][2]['statusName'] == 'Open');
//case2
$new = (!$open &&
($rma_data['status'][0]['statusName'] == 'New' ||
$rma_data['status'][1]['statusName'] == 'New' ||
$rma_data['status'][2]['statusName'] == 'New' ));
if($open){
echo 'open';
}elseif($new){
echo 'New';
}else{
echo 'None';
}
}
Second:
foreach($rma_data['status'] as $key => $val){
$statusName = $val['statusName'];
$newarray[$statusName] = $val;
}
echo '<pre>';
print_r($newarray);
if(array_key_exists('Open', $newarray)){
$created = $newarray['Open']['created'];
$statusId = $newarray['Open']['statusId'];
echo 'Open';
}
elseif(array_key_exists('New', $newarray)){
$created = $newarray['New']['created'];
$statusId = $newarray['New']['statusId'];
echo 'New';
}else{
echo "None";
}

Related

check exist all value every single key in array?

i have an $arrays array like this :
Array
(
[0] => Array
(
[0] => VUM
[1] => UA0885
)
[1] => Array
(
[0] => VUA
[1] => UA0885
)
)
i want to check if input value exist (VUA & UA0885), than not add it to this array.
Ex:
(VUA & UA0885) => not add
(VUB & UA0885) => add
(VUA & UA0886) => add
here is my code:
foreach($arrays as $array){
if($array[0] != $_REQUEST['tourcode'] || $array[1] != $_REQUEST['promocode']){
$arrays[] = array($_REQUEST['tourcode'],$_REQUEST['promocode']);
}
}
Tried use in_array too but it still add a duplicate to $arrays
You can iterate the array, check if the same values are found, and if not push the new values:
$tour = $_REQUEST['tourcode'];
$promo = $_REQUEST['promocode'];
$new = true; //default to true
foreach($arrays as $el){
if($el[0].'-'.$el[1] == $tour. '-' .$promo]){
$new=false;
break; //no need to continue
}
}
if($new) $arrays[]=[$tour,$promo];
foreach($arrays as $key => $array) {
if($array[0] == $_REQUEST['tourcode'] && $array[1] == $_REQUEST['promocode']) {
unset($arrays[$key]);
}
}
To check if there is an entry with tourcode AND promocode already in the array you can use something close to what you had:
function codeInArray($array, $tourcode, $promocode) {
foreach ($array as $entry) {
// check if we have an entry that has the same tour and promo code
if ($entry[0] == $tourcode && $entry[1] == $promocode) {
return true;
}
}
return false;
}
Then you can use it like this:
// run the function and see if its not in the array already
if (!codeInArray($arrays, $_GET['tourcode'], $_GET['promocode'])) {
// add the new entry to `$arrays`
$arrays[] = [
$_GET['tourcode'],
$_GET['promocode'],
];
}
As I understood changing your statement for !in_array might be the solution:
if (!in_array(array($_REQUEST['tourcode'],$_REQUEST['promocode']),$array))
<?php
$array = array(
0=>array(
0=>'VUM',
1=>'UA0885'
),
1=>array(
0=>'VUA',
1=>'UA0885'
)
);
$tour_code = trim($_REQUEST['tourcode']);
$promo_code = trim($_REQUEST['promocode']);
$filterarray = array();
$counter = 0;
foreach($array as $subarray){
foreach($subarray as $key => $value){
if(!in_array($tour_code , $subarray) || !in_array($promo_code , $subarray)){
$filterarray[$counter][] = $value;
}
}
$counter++;
}
print_r($filterarray);
?>

Search nested multidimensional array

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;

php operands in arrays

Hi Guys have the following arrays:
Array
(
[0] => Array
(
[SERIAL] => 1
[SCORE_1] => 6.6490630173025
[SCORE_2] => 13.010510864225
[SCORE_3] => 7.5543177306323
[SCORE_4] => 4.1576775823101
[SCORE_5] => 5.3696604808987
)
[1] => Array
(
[SERIAL] => 2
[SCORE_1] => 11.861835175219
[SCORE_2] => 0
[SCORE_3] => 1.988806017442
[SCORE_4] => 0.97387338276326
[SCORE_5] => 4.0322016758707
)
I need to find the proportion of each element in its array i.e. for example SCORE_1/(SCORE_1+...+SCORE_5) and the serials remain as is. The PHP code looks like this:
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
if($dataRow[$row][$columnKey]==0){
$namedDataArray[$r][$columnHeading] = 0;
}elseif($columnHeading=='SERIAL' ){
$namedDataArray[$r][$columnHeading]=$dataRow[$row][$columnKey];
} else {
$x=(float)1.35;
$a=pow($dataRow[$row][$columnKey],$x);
$namedDataArray[$r][$columnHeading] = $a;
}
}
}
}
echo '<pre>';
print_r($namedDataArray);
echo '</pre><hr />';
I'm still new to php and have been struggling with this one. I used PHPExcel to read the file and raise each element to the power of 1.35 . I've used $total=array_sum($namedDataArray) but when I try to divide i.e$Score= $namedDataArray/$total it says unsupported operand type.
On this line :
$Score= $namedDataArray/$total
$namedDataArray is an array. PHP doesn't allow you to perform a division with an array, you have to put a number instead, for i.e. $Score = $namedDataArray[0]['SCORE_1'] / $total

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

Help with Array List - PHP MYSQL

I have an array value like this.
My print_r($_POST) looks like this.
I can get the post count value too. (Here the count value is 3)
Array ( [tag] => Array ( [4-a] => User1 [8-a] => User2 [3-a] => User3 ))
Now, i want the above array values in a single string.
For ex:
$all_users = User1,User2,User3
Is this possible . Pl advice.
Haan
$all_users = implode(',',$your_array);
If i understand your question well...
$array = Array ( 'tag' => Array ( '4-a' => 'User1', '8-a' => 'User2', '3-a' => 'User3' ));
$allUsers = '';
$first = true;
foreach($array['tag'] as $key=>$value) {
if($first == false) {
$allUsers .= ',' . $value;
} else {
$allUsers .= $value;
}
$first = false;
}
echo $allUsers;

Categories