Count the number of occurences of a particular value inside loop - php

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']++;
}
}

Related

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

Change an array value if duplicate

I have an array which holds some articles of a website. The problem is: when the same article is in 2 different categories it only shows 1. In this example the categories are 'Service' and 'Sales'.
If the article is duplicate and the category is 'Sales' I want 1 of them to change to 'Service' and vice versa.
The array I got now(3 & 4 as duplicates and 7 & 8):
Array
(
[0] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/38BbjLmVJXk
[3] => Park assist
)
[1] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/3lGfTZdVK1s
[3] => Multi Collision braking system
)
[2] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/6mgDraWpGvE
[3] => Area view
)
[3] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/II68oVm4zro
[3] => Lane Assist
)
[4] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/II68oVm4zro
[3] => Lane Assist
)
[5] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/N0fa4dUBkvE
[3] => Trailer assist
)
[6] => Array
(
[0] => Service
[1] => veilig-op-de-weg
[2] => www.youtube.com/video/NCNDyW6Yr1g
[3] => Ruitenwissers
)
[7] => Array
(
[0] => Service
[1] => veilig-op-de-weg
[2] => www.youtube.com/video/PJEC-yqUwzE
[3] => Bandenafdichtset
)
[8] => Array
(
[0] => Service
[1] => veilig-op-de-weg
[2] => www.youtube.com/video/PJEC-yqUwzE
[3] => Bandenafdichtset
)
)
The array I want to accomplish (No duplicates anymore and the values changed):
Array
(
[0] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/38BbjLmVJXk
[3] => Park assist
)
[1] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/3lGfTZdVK1s
[3] => Multi Collision braking system
)
[2] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/6mgDraWpGvE
[3] => Area view
)
[3] => Array
(
[0] => Service
[1] => assistentiesystemen
[2] => www.youtube.com/video/II68oVm4zro
[3] => Lane Assist
)
[4] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/II68oVm4zro
[3] => Lane Assist
)
[5] => Array
(
[0] => Sales
[1] => assistentiesystemen
[2] => www.youtube.com/video/N0fa4dUBkvE
[3] => Trailer assist
)
[6] => Array
(
[0] => Service
[1] => veilig-op-de-weg
[2] => www.youtube.com/video/NCNDyW6Yr1g
[3] => Ruitenwissers
)
[7] => Array
(
[0] => Sales
[1] => veilig-op-de-weg
[2] => www.youtube.com/video/PJEC-yqUwzE
[3] => Bandenafdichtset
)
[8] => Array
(
[0] => Service
[1] => veilig-op-de-weg
[2] => www.youtube.com/video/PJEC-yqUwzE
[3] => Bandenafdichtset
)
)
What I tried:
$length = count ($sorted);
for ($c = 0; $c < $length; $c++) {
$check_array = $sorted[$c];
for ($x = 0; $x < $length; $x++) {
$compare_array = $sorted[$x];
if ($x != $i){
if($check_array[2] == $compare_array[2] && $check_array[0] == $compare_array[0]){
//print_r ($check_array);
//print_r ($compare_array);
if($check_array[0] == 'Sales'){
$compare_array[0] = 'Service';
}
if($check_array[0] == 'Service'){
$compare_array[0] = 'Sales';
}
}
}
}
}
Any help will be much appreciated.
Put your data in $array variable and try it:
$hash = array_map( function ( $value ) { return md5( implode( $value ) ); } , $array);
$keys = array_keys( array_diff_assoc( $hash, array_unique( $hash ) ) );
foreach( $keys as $key )
$array[ $key ][0] = $array[ $key ][0] == 'Service' ? 'Sales' : 'Service';
If the order is not important for you, you can use array_multisort, array_column and array_walk:
$replacements = [
'Sales' => 'Service',
'Service' => 'Sales'
];
// Sort array by youtube url.
array_multisort($array, array_column($array, 2));
array_walk($array, function (&$curr, $_, &$prev) use ($replacements) {
if (
$prev !== null
&& $prev[2] === $curr[2]
) {
$curr[0] = $replacements[$curr[0]];
}
$prev = $curr;
}, null);
Here is working demo.
Here I have a written some code, you can try it.
<?php
$array = [
[
0 => 'Sales',
1 => 'assistentiesystemen',
2 => 'www.youtube.com/video/38BbjLmVJXk',
3 => 'Park assist',
],
[
0 => 'Sales',
1 => 'assistentiesystemen',
2 => 'www.youtube.com/video/3lGfTZdVK1s',
3 => 'Multi Collision braking system'
],
[
0 => 'Sales',
1 => 'assistentiesystemen',
2 => 'www.youtube.com/video/6mgDraWpGvE',
3 => 'Area view'
],
[
0 => 'Sales',
1 => 'assistentiesystemen',
2 => 'www.youtube.com/video/II68oVm4zro',
3 => 'Lane Assist'
],
[
0 => 'Sales',
1 => 'assistentiesystemen',
2 => 'www.youtube.com/video/II68oVm4zro',
3 => 'Lane Assist'
],
[
0 => 'Sales',
1 => 'assistentiesystemen',
2 => 'www.youtube.com/video/N0fa4dUBkvE',
3 => 'Trailer assist'
],
[
0 => 'Service',
1 => 'veilig-op-de-weg',
2 => 'www.youtube.com/video/NCNDyW6Yr1g',
3 => 'Ruitenwissers'
],
[
0 => 'Service',
1 => 'veilig-op-de-weg',
2 => 'www.youtube.com/video/PJEC-yqUwzE',
3 => 'Bandenafdichtset'
],
[
0 => 'Service',
1 => 'veilig-op-de-weg',
2 => 'www.youtube.com/video/PJEC-yqUwzE',
3 => 'Bandenafdichtset'
]
];
/**
* #param $firstIndexValue
* #param $thirdIndexValue
* #param $searchArray
* #return bool
*/
function isExistValue($firstIndexValue, $thirdIndexValue, $searchArray)
{
foreach ($searchArray as $element) {
if ($firstIndexValue == $element[0] && $thirdIndexValue == $element[3]) {
return true;
}
}
return false;
}
$newArray = [];
foreach ($array as $arr) {
$isExist = isExistValue($arr[0], $arr[3], $newArray);
if ($isExist) {
if ($arr[0] == 'Sales') {
$arr[0] = 'Service';
} elseif ($arr[0] == 'Service') {
$arr[0] = 'Sales';
}
}
$newArray[] = $arr;
}
var_dump($newArray);

How can I create a function to display an array as a tree?

How can I create a function to display an array as a tree. For example I want to obtain a decision tree which I want to walk until I get to the leafs based on the branch's values. I create the tree like bellow:
$tree= new DS_Tree();
$node=array('name' => 'start');
$tree->insert_node($node);
$tree->goto_root();
$mytree = new id3();
$mytree->init($data_array_AttrList,$data_array_values,$data_class,$data_array_instances,$tree);
$mytree->run();
echo '<pre class="brush: php">';
print_r($mytree->tree->draw_tree());
echo '</pre>';
The function draw_tree() is:
public function draw_tree() {
return $this->nodes;
}
The function that creates my tree is:
private function make_tree($attr) {
foreach($this->Values[$attr] as $v) {
$subset = $this->get_subset($attr, $v);
if($the_class = $this->has_same_class($subset)) {
$node =array(
'name' => $attr,
'arc' => $v
);
$this->tree->insert_node($node);
$this->Instance = array_diff_key($this->Instance, $subset);
} else {
$node =array(
'name' => $this->Classa,
'arc' => $v
);
$unresolved = $this->tree->insert_node($node);
}
}
if (isset($unresolved)) {
$this->tree->goto_index($unresolved);
}
}
}
The result is:
Array
(
[0] => Array
(
[name] => Time
[parent] =>
[children] => Array
(
[0] => 1
)
)
[1] => Array
(
[name] => Focus
[arc] => Array
(
[0] => 2 day/week
[1] => 3 day/week
[2] => 4 day/week
[3] => 5 day/week
[4] => 6 day/week
)
[parent] => 0
[children] => Array
(
[0] => 2
)
)
[2] => Array
(
[name] => Dificulty
[arc] => Array
(
[0] => Weght loss
[1] => Mantain weight
[2] => Gain Mass
)
[parent] => 1
[children] => Array
(
[0] => 3
)
)
[3] => Array
(
[name] => Sex
[arc] => Array
(
[0] => Beginner
[1] => Intermediar
[2] => Advance
)
[parent] => 2
[children] => Array
(
[0] => 4
)
)
[4] => Array
(
[name] => Array
(
[Exercise] => Array
(
[0] => Array
(
[0] => Ex1
[1] => Ex2
[2] => Ex3
[3] => Ex4
[4] => Ex5
)
)
)
[arc] => Array
(
[0] => F
[1] => M
)
[parent] => 3
)
)
Just to display an array as a tree:
echo "<pre>";
var_dump($array);
echo "</pre>";
Here is a way to iterate through this data structure and look for a certain value:
function recurseFind($tree, $find, $path = "") {
if (!is_array($tree)) {
// it is a leaf:
if ($tree === $find) {
return $path; // return path where we found it
}
return false;
}
foreach($tree as $key => $value) {
$result = recurseFind($value, $find, $path . (is_numeric($key) ? "[$key]" : "['$key']"));
if ($result !== false) return $result;
}
return false;
}
For the sample input you provided, if you would call it like this:
echo recurseFind($tree, "Mantain weight", '$tree');
Outputs the "location" of that value (first match only) in a format that can be evaluated in PHP:
$tree[2]['arc'][1]

PHP-Smartest Multidimensional array filter

I have a multidimensional array as follows
Array
(
[0] => Array
(
[1] => val01
[2] => val02
[3] =>
)
[1] => Array
(
[1] => val11
[2] => Array
(
[sub1] => 1
[sub2] =>
[sub3] => Array
(
[primarysub1] =>
[primarysub2] => pmy2
)
)
[3] => val3
)
[2] => Array
(
[1] => val21
[2] =>
[3] => val23
)
)
And I need to filter the empty values and expected output is as follow.
Array
(
[0] => Array
(
[1] => val01
[2] => val02
)
[1] => Array
(
[1] => val11
[2] => Array
(
[sub1] => 1
[sub3] => Array
(
[primarysub2] => pmy2
)
)
[3] => val3
)
[2] => Array
(
[1] => val21
[3] => val23
)
)
Could somebody help me out with a best way using PHP?
You have to use recursive function for this. hope this might help you
<?php
$rs = unsetValues($arr);
function unsetValues($a)
{
foreach($a as $k=>$v)
{
if(is_array($v))
{
$arr2[$k] = unsetValues($v);
} else {
if($v!="")
$arr2[$k] = $v;
}
}
return $arr2;
}
?>
function filter($input, $callback = null)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = filter($value, $callback);
}
}
return array_filter($input, $callback);
}
function remove_empty($val)
{
return !empty($val);
}
$test_arr = array(
0 => array(1 => "val01", 2 => "val02", 3 => ""),
1 => array(1 => "val11", 2 => array("sub1" => 1, "sub2" => "", "sub3" => array("primarysub1" => "", "primarysub2" => "pmy2")), 3 => "val3"),
2 => array(1 => "val21", 2 => "", 3 => "val23")
);
echo '<pre>' . print_r($test_arr, true) . '</pre>';
// filter empty
$result = filter($test_arr, remove_empty);
echo '<pre>' . print_r($result, true) . '</pre>';

Sorting through array for to find match

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.

Categories