Count from two array php - php

I have two array, arrLevel1 and arrLevel2.
I want to count animal that can walk.
How can I do that array stucture like this?
Thx before. I already tried, but it failed.
arrLevel1:
array(4) {
[0]=>
array(1) {
["Walk"]=>
string(4) "Bird"
}
[1]=>
array(1) {
["Walk"]=>
string(3) "Cat"
}
[2]=>
array(1) {
["Fly"]=>
string(9) "ButterFLy"
}
[3]=>
array(1) {
["Fly"]=>
string(4) "Bird"
}
}
arrLevel2:
array(3) {
[0]=>
array(1) {
["Animal"]=>
string(3) "Fly"
}
[1]=>
array(1) {
["Animal"]=>
string(11) "Walk"
}
[2]=>
array(1) {
["Human"]=>
string(11) "Walk"
}
}

Just check them in a loop
For the first arrLevel1:
<?php
$arrLevel1 = array(array("walk"=>"Bird"),array("walk"=>"Cat"),array("Fly"=>"Butterfly"),array("Fly"=>"Bird"));
$x = 0;
foreach($arrLevel1 as $p){
if($p["walk"]!==null){
$x++;
}
}
var_dump($x);
?>
Hope thsi helps you

One way to do it is using array_reduce():
$array = array(array('Walk' => 'Bird'), array('Walk' => 'Cat'), array('Fly' => 'ButterFly'), array('Fly' => 'Bird'));
$count = array_reduce($array, function($carry, $item) {
return key($item) == 'Walk' ? $carry + 1 : $carry;
}, 0);
var_dump($count);
You can use a similar code for the second version:
$array = array(array('Animal' => 'Fly'), array('Animal' => 'Walk'), array('Human' => 'Walk'));
$count = array_reduce($array, function($carry, $item) {
return reset($item) == 'Walk' ? $carry + 1 : $carry;
}, 0);
var_dump($count);

Related

Merge 2 arrays in PHP in a specific way by taking one key from each

Struggling to find the logic to merge 2 arrays in a specific way for example I have
array('lemons', 'oranges', 'grapes', 'pineapples');
and
array('carrots', 'onions', 'cabbage');
and I want to end up with
array('lemons', 'carrots', 'oranges', 'onions', 'grapes', 'cabbage' 'pineapples');
I.e to merge them in a one from each way rather than just together at the end and start.
$x = 0;
while ($x < max(count($fruit), count($veg))) {
if (isset($fruit[$x])) {
$merged[] = $fruit[$x];
}
if (isset($veg[$x])) {
$merged[] = $veg[$x];
}
$x++;
}
something like that?
Not the most sophisticated answer, but this is what I have come up with.
$array1 = array('lemons', 'oranges', 'grapes', 'pineapples');
$array2 = array('carrots', 'onions', 'cabbage');
$iterator = 0;
// Continue until the end of both arrays
while (!empty($array1) || !empty($array2)) {
// If iterator is odd then we want the second array, or if array one is empty
if ($iterator++ % 2 == 1 && !empty($array2) || empty($array1)) {
$array3[] = array_shift($array2);
} else {
$array3[] = array_shift($array1);
}
}
var_dump($array3);
Output:
array('lemons', 'carrots', 'oranges', 'onions', 'grapes', 'cabbage' 'pineapples');
Loop over the indexes (from 0 to max(count($array1), count($array2))), then in the loop statement, append the indexed element of each array to a new one, if they are set.
Try something like this:
$ar1 = array('lemons', 'oranges', 'grapes', 'pineapples');
$ar2 = array('carrots', 'onions', 'cabbage');
function mergeCustom($ar1, $ar2) {
$newAr = array();
foreach ($ar1 as $key => $item) {
array_push($newAr, $item);
if (!empty($ar2[$key])) {
array_push($newAr, $ar2[$key]);
}
}
// if length of second array is greater then first one
while(!empty($ar2[$key])) {
array_push($newAr, $ar2[$key]);
$key++;
}
return $newAr;
}
var_dump(mergeCustom($ar1, $ar2), mergeCustom($ar2, $ar1));
Output will be:
array(7) {
[0]=>
string(6) "lemons"
[1]=>
string(7) "carrots"
[2]=>
string(7) "oranges"
[3]=>
string(6) "onions"
[4]=>
string(6) "grapes"
[5]=>
string(7) "cabbage"
[6]=>
string(10) "pineapples"
}
array(8) {
[0]=>
string(7) "carrots"
[1]=>
string(6) "lemons"
[2]=>
string(6) "onions"
[3]=>
string(7) "oranges"
[4]=>
string(7) "cabbage"
[5]=>
string(6) "grapes"
[6]=>
string(6) "grapes"
[7]=>
string(10) "pineapples"
}

Count multidimensional array

I have my main array:
array(6) {
[1]=> array(3) {
[0]=> string(15) "Extension"
[1]=> int(1)
[2]=> string(6) "3,00 "
}
[2]=> array(3) {
[0]=> string(32) "Physics "
[1]=> string(1) "1"
[2]=> string(6) "3,00 "
}
[3]=> array(3) {
[0]=> string(31) "Physics "
[1]=> int(1)
[2]=> string(6) "6,00 "
}
[4]=> array(3) {
[0]=> string(34) "Desk"
[1]=> int(4)
[2]=> string(8) "127,00 "
}
[5]=> array(3) {
[0]=> string(18) "assistance"
[1]=> int(1)
[2]=> string(7) "12,50 "
}
[6]=> array(3) {
[0]=> string(15) "Extension"
[1]=> int(1)
[2]=> string(6) "3,00 "
}
}
My expected output is:
Extension 2
Physics 2
Desk 1
Assistance 1
The result must be in an resultarray
How can I do? I tried with array_count_values function but don't work.
How can I stock answear:
I tried this code but It doesn't work
$tabrecap = array();
foreach($counts as $key=>$value){
//echo $key." qte".$value;
$tabrecap = array ($key,$value,$valueOption);
}
As you asked in comment,Please try this:-
<?php
$array = array( '1'=> array('0'=>"Extension", '1'=> 1, '2'=>"3,00 " ), '2'=> array('0'=>"Physics",'1'=>"1","3,00 " ),'3'=> array('0'=>"Physics",'1'=>1,"6,00 "),'4'=> array('0'=>"Desk",'1'=>4,"127,00 "),'5'=> array('0'=>"assistance",'1'=>1,"12,50 " ),'6'=> array('0'=>"Extension",'1'=>1,"3,00 "));
$count = array();
$i = 0;
foreach ($array as $key=>$arr) {
// Add to the current group count if it exists
if (isset($count[$i][$arr[0]])) {
$count[$i][$arr[0]]++;
}
else $count[$i][$arr[0]] = 1;
$i++;
}
print_r($count);
?>
Output:- https://eval.in/379176
Looping is the answer.
<?php
// untested
$counts = Array();
foreach( $array as $subArray ){
$value = $subArray[0];
$counts[ $value ] = ( isset($counts[ $value ]) )
? $counts[ $value ] + 1
: 1;
}
var_dump( $counts);
Just make a loop and use first item of each array as key :
$array = array(
array("Extension", 1, "3,00"),
array("Physics", "1", "3,00"),
array("Physics", 1, "6,00 ")
);
$count = array();
foreach($array as $a)
$count[$a[0]]++;
var_dump($count); // array(2) { ["Extension"]=> int(1) ["Physics"]=> int(2) }

Sorting infinite depth array - php

I have the following array: (ordered by parent_id)
array(9) {
[1]=>
array(3) {
["name"]=>
string(6) "Tennis"
["parent_id"]=>
NULL
["depth"]=>
int(0)
}
[7]=>
array(3) {
["name"]=>
string(11) "TOP LEVEL 2"
["parent_id"]=>
NULL
["depth"]=>
int(0)
}
[8]=>
array(3) {
["name"]=>
string(11) "TOP LEVEL 3"
["parent_id"]=>
NULL
["depth"]=>
int(0)
}
[2]=>
array(3) {
["name"]=>
string(5) "Shoes"
["parent_id"]=>
string(1) "1"
["depth"]=>
int(1)
}
[3]=>
array(3) {
["name"]=>
string(5) "Women"
["parent_id"]=>
string(1) "2"
["depth"]=>
int(2)
}
[4]=>
array(3) {
["name"]=>
string(4) "Mens"
["parent_id"]=>
string(1) "2"
["depth"]=>
int(2)
}
[5]=>
array(3) {
["name"]=>
string(12) "Mens Running"
["parent_id"]=>
string(1) "4"
["depth"]=>
int(3)
}
[6]=>
array(3) {
["name"]=>
string(11) "Mens Tennis"
["parent_id"]=>
string(1) "4"
["depth"]=>
int(3)
}
[9]=>
array(3) {
["name"]=>
string(9) "2nd level"
["parent_id"]=>
string(1) "8"
["depth"]=>
int(1)
}
}
I want to sort it in a way that it can be used in a drop down menu. The format for a drop down menu is:
$categories[$CATEGORY_ID] = str_repeat(' ', $value['depth']).$value['name'];
The above array up top is sorted by parent_id where top levels have a parent_id of NULL.
I need to sort it in such a way that the array is in order. For example:
[1] => 'Tennis';
[2] => ' &nbspShoes'
[3] => ' Womens'
[4] => ' Men'
[5] => ' Mens Running
[6] => ' Mens Tennis
[7] => 'TOP LEVEL 2'
[8] => 'TOP LEVEL 3'
[9] => ' 2nd level'
I tried this:
function get_all_categories_and_subcategories($parent_id = NULL, $depth = 0)
{
$categories = $this->get_all($parent_id, 10000, 0, 'parent_id');
if (!empty($categories))
{
$unique_parent_ids = array();
foreach($categories as $id => $value)
{
$categories[$id]['depth'] = $depth;
$unique_parent_ids[$id] = TRUE;
}
foreach(array_keys($unique_parent_ids) as $id)
{
$categories = array_replace($categories, $this->get_all_categories_and_subcategories($id, $depth + 1));
}
return $categories;
}
else
{
return $categories;
}
}
function sort_categories($categories)
{
usort($categories, array('Category','do_sort_categories'));
return $categories;
}
static function do_sort_categories($a, $b)
{
$al = strtolower($a['parent_id']);
$bl = strtolower($b['parent_id']);
if ($al == $bl) {
return 0;
}
return ($al > $bl) ? +1 : -1;
}
function get_all($parent_id = NULL, $limit=10000, $offset=0,$col='name',$order='asc')
{
$this->db->from('categories');
if (!$this->config->item('speed_up_search_queries'))
{
$this->db->order_by($col, $order);
}
if ($parent_id === NULL)
{
$this->db->where('parent_id IS NULL', null, false);
}
else if($parent_id)
{
$this->db->where('parent_id', $parent_id);
}
$this->db->limit($limit);
$this->db->offset($offset);
$return = array();
foreach($this->db->get()->result_array() as $result)
{
$return[$result['id']] = array('name' => $result['name'], 'parent_id' => $result['parent_id']);
}
return $return;
}
I don't have the possibility to test this code right now, but you could try something like this (and correct from my comments if needed).
Hope it would help a bit.
$objects = array();
// turn to array of objects to make sure our elements are passed by reference
foreach ($array as $k => $v) {
$node = new StdClass();
$node->id = $k;
$node->parent_id = $v['parent_id'];
$node->name = $v['name'];
$node->depth = $v['depth'];
$node->children = [];
$objects[$k] = $node;
}
// list dependencies parent -> children
foreach ($objects as $node)
{
$parent_id = $node->parent_id;
if ($parent_id !== null)
{
$object[$parent_id][] = $node;
}
}
// sort children of each node
foreach ($objects as $node)
{
usort($node->children, function($a, $b){
return $a->id < $b->id;
});
}
// clean the object list to make kind of a tree (we keep only root elements)
$sorted = array_filter($objects, function($node){
return $node->depth === 0;
});
// flatten recursively
function flatten_node(&$node) {
return array_merge([$node], flatten($node->children));
}
array_walk($sorted, 'flatten_node');
// $sorted is a sorted list of objects (not array as defined at the beginning).
// You could turn it back to array and remove the 'children' key that was
// only used for sorting purposes.

Merge arrays. Second array as a "column"

Here is an example...
I have the following code:
$a=array("a","b","c");
$b=array("1","2","3");
$c = array_merge($a,$b);
echo "<pre>";
var_dump($c);
echo "</pre>";
Gives me an output:
array(6) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "1"
[4]=>
string(1) "2"
[5]=>
string(1) "3"
}
How could I change the code so that it gives me this output instead:
array(3) {
[0]=>
string(5) "a','1"
[1]=>
string(5) "b','2"
[2]=>
string(5) "c','3"
Any ideas?
$c = array_map(function ($a, $b) { return "$a','$b"; }, $a, $b);
For whatever that's good for...
Using SPL's MultipleIterator:
$a = array("a","b","c");
$b = array("1","2","3");
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$c = array();
foreach($mi as $row) {
$c[] = $row[0] . "','" . $row[1];
}
var_dump($c);
If the keys to both arrays are always in parity, you could do something like
foreach ($a as $key => $value) {
$newArray[] = "$value','{$b[$key]}";
}
var_dump($newArray);
// would output the below
array(3) {
[0]=>
string(5) "a','1"
[1]=>
string(5) "b','2"
[2]=>
string(5) "c','3"
However, the result looks a little weird, are you sure this is what you are trying to achieve?
$a=array("a","b","c");
$b=array("1","2","3");
if(count($a) > count($b)){
foreach($a as $key => $value)
$c[$key] = isset($b[$key])? $value.",".$b[$key] : $value;
} else {
foreach($b as $key => $value)
$c[$key] = isset($a[$key])? $a[$key].",".$value : $value;
}
Use above code it will for your array.

Merge two arrays with the same key but in different depth?

$arr = array('one' => array('one_1' => array('one_2' => '12')), 'two', 'three');
$arr2 = array('one_2' => 'twelve');
$merge = array_merge($arr, $arr2);
print '<pre>';
var_dump($merge);
print '</pre>';
gives:
array(4) {
["one"]=>
array(1) {
["one_1"]=>
array(1) {
["one_2"]=>
string(2) "12"
}
}
[0]=>
string(3) "two"
[1]=>
string(5) "three"
["one_2"]=>
string(6) "twelve"
}
I want the value of key one_2 in the first array to be replaced with the value of the same key in the second array. So the result would be:
array(4) {
["one"]=>
array(1) {
["one_1"]=>
array(1) {
["one_2"]=>
string(2) "twelve"
}
}
[0]=>
string(3) "two"
[1]=>
string(5) "three"
}
array_walk_recursive($arr, function (&$value, $key, $replacements) {
if (isset($replacements[$key])) {
$value = $replacements[$key];
}
}, $arr2);
Note that this uses PHP 5.3+ syntax.

Categories