Sorting through array for to find match - php

I have two arrays like this
Array
(
[0] => MYU_MP1
[1] => 4cc00e5f580f00c2e54193fde7129608
[2] => da8bbfdb40be0dc2b3312ca1037f994a
[3] => d4cfaa8db24c4b81db506189360b6b99
)
Array
(
[0] => MYU_SC1
[1] => MYU_SC2
[2] => MYU_SF1
[3] => MYU_SC3
[4] => MYU_AD1
[5] => MYU_AD2
[6] => MYU_AD3
[7] => MYU_AD4
[8] => MYU_RC1
[9] => MYU_RC2
[10] => MYU_RC3
[11] => MYU_RC4
[12] => MYU_RC5
[13] => MYU_RC6
[14] => MYU_RC7
[15] => MYU_RC8
)
the first one aliased as "deliverable" and the other "non_deliverable"
and a third array
Array
(
[d8df18561040f3d9bd9868f5c5aaa7c2] => Array
(
[rowid] => d8df18561040f3d9bd9868f5c5aaa7c2
[id] => MYU_SC1
[qty] => 1
[price] => 500
[name] => WAEC Scratch Card
[service_image] => assets/img/waec.jpg
[service_category] => scratch_cards
[subtotal] => 500
)
the third array is aliased "cart_items"
[f68964856a61092d9a2566d024a0ba28] => Array
(
[rowid] => f68964856a61092d9a2566d024a0ba28
[id] => MYU_MP1
[qty] => 1
[price] => 210000
[name] => Apple iPhone 5 16gb
[service_image] =>
[service_category] => mobile-phones
[subtotal] => 210000
)
)
I have written a function that supposed to loop through the third array to determine if an "id" element of the third array is member of the first or second array
//sort through cart items
foreach ($cart_items as $key => $item) {
if(in_array($item['id'], $deliverables) && in_array($item['id'], $non_deliverables)) {
$deliverable = TRUE;
$non_deliverable = TRUE;
}
if(in_array($item['id'], $deliverables) && !in_array($item['id'], $non_deliverables)) {
$deliverable = TRUE;
}
if(in_array($item['id'], $non_deliverables) && !in_array($item['id'], $deliverables)) {
$non_deliverable = TRUE;
}
if($deliverable && $non_deliverable)
$type = "both";
if($non_deliverable)
$type = "non-deliverable";
if($deliverable)
$type = "deliverable";
}
return $type;
But when the third array has matches in both the 1st and 2nd array the function returns "deliverable". What am i not doing right?

function somefunction()
foreach ($cart_items as $key => $item) {
$deliverable = in_array($item['id'], $deliverables);
$non_deliverable = in_array($item['id'], $non_deliverables);
$type = "none";
if ($deliverable && $non_deliverable) {
$type = "both";
} elseif ($deliverable && !$non_deliverable) {
$type = "deliverable";
} elseif (!$deliverable && $non_deliverable) {
$type = "non-deliverable";
}
}
return $type;
}

Your sortorder is wrong. The check for $deliverable and $non_deliverable should be the last. Alternatively you could use an if-else-if-else structure.

Related

convert nested foreach tree into recursive php function

Need to make recursive function from the below code. tried multiple ways but failed. because I don't know how much depth will the tree have. depth may be varying according to the data.
$tot_terms = [];
foreach ($tree as $key => $val) {
$tot_terms[$val->depth][] = $val->tid;
if (!empty($val->children)) {
foreach ($val->children as $key1 => $val1) {
$tot_terms[$val1->depth][] = $val1->tid;
if ($val1->children) {
foreach ($val1->children as $key2 => $val2) {
$tot_terms[$val2->depth][] = $val2->tid;
if ($val2->children) {
foreach ($val2->children as $key3 => $val3) {
$tot_terms[$val3->depth][] = $val3->tid;
if ($val3->children) {
foreach ($val3->children as $key4 => $val4) {
$tot_terms[$val4->depth][] = $val4->tid;
if ($val4->children) {
foreach ($val4->children as $key5 => $val5) {
$tot_terms[$val5->depth][] = $val5->tid;
}
}
}
}
}
}
}
}
}
}
}
and the result should be like this
Array
(
[0] => Array
(
[0] => 20011
[1] => 19991
[2] => 20000
)
[1] => Array
(
[0] => 20010
[1] => 19995
[2] => 19994
[3] => 19990
[4] => 20005
[5] => 19985
[6] => 19999
[7] => 19998
)
[2] => Array
(
[0] => 20012
[1] => 20006
[2] => 19996
[3] => 19993
[4] => 19989
[5] => 19988
[6] => 20004
[7] => 19984
[8] => 20001
)
[3] => Array
(
[0] => 20007
[1] => 20009
[2] => 20008
[3] => 19992
[4] => 19987
[5] => 19986
[6] => 19983
[7] => 19982
[8] => 20003
[9] => 20002
)
[4] => Array
(
[0] => 19997
)
[5] => Array
(
[0] => 19981
)
)
Tried according to other post but it is failing. input $tree is something that is array and an object. will post in next comment if required as total body count is more than its expected
We can use a handler function to store data. Note that we are passing the array by reference.
function func( $item, &$data ) {
if ( is_empty( $item ) ) return;
if ( ! is_object( $item ) ) return;
foreach ($item as $key => $val) {
$data[$val->depth][] = $val->tid;
func( $val->children, $data );
}
}
function func_handler( $item ) {
$data = [];
func( $item, $data );
return $data;
}

Convert PHP array to new data-structure

I have a MYSQL query which returns the following PHP array $result:
[0] => Array (
[resourceKey] => cloth
[date] => 2020-09-06
[quantity] => 8
)
[1] => Array (
[resourceKey] => ebony
[date] => 2020-09-06
[quantity] => 4
)
[2] => Array (
[resourceKey] => gems
[date] => 2020-09-06
[quantity] => 0
)
[3] => Array (
[resourceKey] => lead
[date] => 2020-09-06
[quantity] => 0
)
[4] => Array (
[resourceKey] => limestone
[date] => 2020-09-06
[quantity] => 8
)
[5] => Array (
[resourceKey] => cloth
[date] => 2020-09-05
[quantity] => 6
)
[6] => Array (
[resourceKey] => ebony
[date] => 2020-09-05
[quantity] => 3
)
[7] => Array (
[resourceKey] => gems
[date] => 2020-09-05
[quantity] => 0
)
[8] => Array (
[resourceKey] => lead
[date] => 2020-09-05
[quantity] => 0
)
[9] => Array (
[resourceKey] => limestone
[date] => 2020-09-05
[quantity] => 6
)
And I need to convert it is a certain way to display it with jquery Datatables:
$data= array(
array("Date" => "2020-09-05","cloth"=>"6","ebony"=>"3","gems"=>"0","lead"=>"0","limestone"=>"6"),
array("Date" => "2020-09-06","cloth"=>"8","ebony"=>"4","gems"=>"0","lead"=>"0","limestone"=>"8")
);
I've been trying for a while now but can't get a good way to iterate through the results...
I have already taken care of building the columns to pass to Datatables:
$columns = array();
$columns[] = array('data' => 'Date', 'title' => 'Date');
foreach ($result as $key => $row_data) {
$newResourceKey = $myUtilities->in_array_recursive($row_data['resourceKey'], $columns);
if ($newResourceKey === FALSE) { // Only if column name not yet in array
$columns[] = array('data' => $row_data['resourceKey'], 'title' => $row_data['resourceKey']);
}
}
This is an example of the many things I've tried:
$isDateInArray = $myUtilities->in_array_recursive($row_data['date'], $data);
if ($isDateInArray === FALSE) { // Only if Date is not in array yet
array_push($data, array('Date' => $row_data['date'], $row_data['resourceKey'] => $row_data['quantity'])); // Push date and data
}
else {
array_push($data, array($row_data['resourceKey'] => $row_data['quantity'])); // Only push data. Can't find a way to add it to existing Date array
}
Update:
public function in_array_recursive($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_recursive($needle, $item, $strict))) {
return true;
}
}
return false;
}
You can get the desired result by next simple array transformation:
$res = [];
foreach ($result as $row) {
$res[$row['date']][$row['resourceKey']] = $row['quantity'];
}
$final = [];
foreach ($res as $d=>$r) {
array_push($final, array_merge(['date'=>$d], $r));
}
print_r($final);
Here you can try the PHP code

how to array push with multidimension in php

I have an array in PHP loop output like this
this is my php code :
$sql = "SELECT * FROM `acc` ";
$stm = $conn->prepare($sql);
$stm->execute();
$array= [];
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$array[]=$row['h_id'];
}
print_r($array);
and output is :
Array
( [0] => 11
[1] => 12
[2] => 13
[3] => 1101
[4] => 1102
[5] => 110101
[6] => 110102
[7] => 1201
[8] => 1202
[9] => 1301
[10] => 1302
[11] => 1303
[12] => 130201
[13] => 130202
[14] => 130301
[15] => 130302
)
and I want to sort and rearrange array to multi-dimension for parent and child with php Loop Like this :
Array
(
[11] => Array
(
[1101] => Array
(
[0] => 110101
[1] => 110102
)
)
[12] => Array
(
[0] => 1201
[1] => 1202
)
[13] => Array
(
[0] => 1301
[1302] => Array
(
[0] => 130201
[1] => 130202
)
[1303] => Array
(
[0] => 130301
[1] => 130302
)
)
how to implemention and push array to another with php.
thanks!
I absolutely don't understand what you're doing, but I think I've grasped how your input may be mapped to desired output. Here is the code:
<?php
$flat = [
11,
12,
13,
1101,
1102,
110101,
110102,
1201,
1202,
1301,
1302,
1303,
130201,
130202,
130301,
130302,
];
function expand($flat)
{
$expanded = [];
foreach ($flat as $element) {
$sections = str_split((string)$element, 2);
$tmp = &$expanded;
$path = '';
foreach ($sections as $section) {
$path .= $section;
if (!isset($tmp[$path])) {
$tmp[$path] = [];
}
$tmp =& $tmp[$path];
}
unset($tmp);
}
return $expanded;
}
function fold($expanded) {
$folded = [];
foreach ($expanded as $key => $value) {
if ($value === []) {
$folded[] = $key;
} else {
$folded[$key] = fold($value);
}
}
return $folded;
};
print_r(fold(expand($flat)));
And here is its output (which is suspiciously close to yours):
Array
(
[11] => Array
(
[1101] => Array
(
[0] => 110101
[1] => 110102
)
[1102] => 1102
)
[12] => Array
(
[0] => 1201
[1] => 1202
)
[13] => Array
(
[0] => 1301
[1302] => Array
(
[0] => 130201
[1] => 130202
)
[1303] => Array
(
[0] => 130301
[1] => 130302
)
)
)
There are some differences, though, e.g. there is element 1102 in your input, but in your sample output it is absent, and I'm not sure if you forgot it or if you have filtered it out for some reason.

Count the number of occurences of a particular value inside loop

In array count all true where category is 1 after counting the category will move to 2 thn count all true and so on?
Array generated:
foreach($_POST as $key => $data)
{
$a = explode("_", $key);
$f = array(
'category' => $a[1],
'answer' => $data
);
$f_data[] = $f;
}
FROM
Array
(
[0] => Array
(
)
[1] => Array
(
[category] => 1
[answer] => true
)
[2] => Array
(
[category] => 1
[answer] => true
)
[3] => Array
(
[category] => 1
[answer] => true
)
[4] => Array
(
[category] => 1
[answer] => false
)
[5] => Array
(
[category] => 1
[answer] => false
)
[6] => Array
(
[category] => 1
[answer] => true
)
[7] => Array
(
[category] => 1
[answer] => true
)
[8] => Array
(
[category] => 2
[answer] => true
)
[9] => Array
(
[category] => 2
[answer] => true
)
[10] => Array
(
[category] => 2
[answer] => true
)
[11] => Array
(
[category] => 2
[answer] => false
)
[12] => Array
(
[category] => 2
[answer] => true
)
[13] => Array
(
[category] => 2
[answer] => true
)
)
To
array (
category: 1,
count: 5
),
array(
category: 2,
count: 5
)
This is the solution :
$return = array();
foreach($cont as $item) {
if($item['answer'] == 'true') {
$verify = false;
foreach($return as $key => $value) {
if($value['category'] == $item['category']) {
$return[$key]['count']++;
$verify = true;
break;
}
}
if(!$verify)
$return[] = array('category' => $item['category'], 'count' => 1);
}
}
And this is better solution...
$return = array();
foreach($cont as $item) {
if($item['answer'] == 'true') {
if(array_key_exists($item['category'], $return))
$return[$item['category']]++;
else
$return[$item['category']] = 1;
}
}
Untested, but I believe this is what you are after (pending any minor mistakes):
foreach($_POST as $key => $data)
{
$a = explode("_", $key);
$f[$a[1]]['category'] = $a[1];
if ($data == "true") {
$f[$a[1]]['answer']++;
}
}

list and count elements in array php

I have the following array and am trying to loop through it with php, generate a list of the "Type" and count how many. The Type is the key, but there will be unique values such as Call, To-do, Meeting, Proposal, etc. My goal is to have the following out put:
Call 2
To-do 1
Meeting 3
Proposal 4
The above are not the values that will be output from the following array, but I wanted you to have an idea of what I am trying to accomplish. Please help!
Array (
[0] => Array (
[0] => Call
[Type] => Call
[1] => fxxxx#xxxxentllc.com
[EmailAddress] => xxxxr#xxxxentllc.com
[2] => 3xxxx00
[Phone] => 31xxxx00
[3] => 31xxxx871
[MobilePhone] => 31xxxx871
[4] => 102795
[CustomerID] => 102795
[5] => Nortxxxxal
[Company] => Noxxxxal
[6] => Frank
[FirstName] => Frank
[7] => Syxxxxer
[LastName] => Sxxxxter
[8] => 3
[Priority] => 3
[9] => invite to Haxxxxales for lunch
[Details] => invite to Hafxxxxales for lunch
[10] => 4503
[ActivityID] => 4503
[11] => 05/23/13
[DueDate] => 05/23/13
)
[1] => Array (
[0] => To-do
[Type] => To-do
[1] => fsxxxxer#summxxxxntllc.com
[EmailAddress] => fsxxxxer#summixxxxtllc.com
[2] => 315xxxx000
[Phone] => 3154xxxx0
[3] => 315xxxx1
[MobilePhone] => 315xxxx1
[4] => 102795
[CustomerID] => 102795
[5] => Norxxxxl
[Company] => Norxxxxcal
[6] => Frxxxxk
[FirstName] => Fxxxxk
[7] => Sxxxxr
[LastName] => Syxxxxer
[8] => 3
[Priority] => 3
[9] => find out who contact is for xxxxdical center
[Details] => find out who contact is foxxxxcal center
[10] => 4504
[ActivityID] => 4504
[11] => 05/23/13
[DueDate] => 05/23/13
)
)
This should do it:
$type_counts = array_count_values(array_map(function($x) {return $x['Type'];}, $array));
The array_map will return an array containing all the Type elements, then array_count_values will count the number of each of these and return this as an associative array.
something along the lines of:
foreach ($array as $key => $value) {
if (isset($result[$key])) {
$result[$key]++;
} else {
$result[$key] = 1;
}
}
if it is a muldi-dimensional array, just put another for each in there but that should give you an idea
$types = array();
foreach($array as $item) {
isset(${$item['Type']}) ? ${$item['Type']}++ : ${$item['Type']} = 1;
if(!in_array($item['Type'], $types) {
$types[] = $item['Type'];
}
foreach($types as $type) {
echo "$type ${$type}\n";
}
I think you can loop in your array and count each occorrence
$Call = 0;
$To_do = 0;
$Meeting = 0;
$Proposal = 0;
foreach($array as $data)
{
if($data['Type'] == 'Call')
{
$Call++;
} else if($data['Type'] == 'To-do')
{
$To_do++;
} else if($data['Type'] == 'Meeting')
{
$Meeting++;
} else if($data['Type'] == 'Proposal')
{
$Proposal++;
}
}
In this way you will have stored in each variable $Call $To_do $Meeting $Proposal its relative count
you can use (array_count_values($array));
http://php.net/manual/en/function.array-count-values.php
This gives count of all the keys in an array.
If you want only for the specific keys then use foreach loop
The one Petros mentioned is the best way to do it.
I would do something along the lines of:
$your_array = /* Your Array */
$types_count = array();
foreach ($your_array as $type_array){
$types_count[$type_array['Type']]++;
}

Categories