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] => '  Shoes'
[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.
Related
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) }
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);
I have this array and I was wondering how can I :
Sum qty so finaly I receive only unique products ids with their qty-s, for example:
product 805 - 1 piece
product 1118 - 2+3+4 = 9pieces
array(2){
["product"]=> array(4){
[0]=> string(3) "805"
[1]=> string(4) "1118"
[2]=> string(4) "1118"
[3]=> string(4) "1118"
}
["qty"]=> array(4) {
[0]=> string(1) "1"
[1]=> string(1) "2"
[2]=> string(1) "3"
[3]=> string(1) "4"
}
}
Thank you in advance,
$productQuantities = array();
$products = array("805","1118","1118","1118");
$quantities = array(1,2,3,4);
foreach($products AS $key=>$productId){
$quantity = (int) $quantities[$key];
if(isset($productQuantities[$productId])){
$productQuantities[$productId] += $quantity;
} else {
$productQuantities[$productId] = $quantity;
}
}
var_dump($productQuantities);
You could try this:
$zipped=array_map(
null,
$your_array['product'],
$your_array['qty']
);
$compact = array();
foreach ($zipped as $k => $v){
if(!array_key_exists($v[0], $compact)){
$compact[$v[0]] = $v[1];
} else {
$compact[$v[0]] += $v[1];
}
}
Then you will find your result in $compact
I try to add product to the shopping cart but I have some problems with the loop logic.
This function should add new product and check if product id is already in the cart. If it is in the cart it should add 1 to existing product or the quantity selected by user.
Here is some code that I have:
function AddToCart($pid, $q)
{
$quantity = $q;
$product_id = $pid;
if (is_array($_SESSION['products']))
{
foreach($_SESSION['products'] as $key => $my_value)
{
if ($pid === $my_value['product_id'])
{
if ($quantity != 1)
{
$quantity = $my_value['quantity'] + $quantity;
$_SESSION['products'][$key]['quantity'] = $quantity;
}
else
{
$quantity = $my_value['quantity'] + 1;
$_SESSION['products'][$key]['quantity'] = $quantity;
}
}
else
{
$_SESSION['products'][] = array(
'product_id' => $product_id,
'quantity' => $quantity,
);
}
}
}
else
{
$_SESSION['products'][] = array(
'product_id' => $product_id,
'quantity' => $quantity,
);
}
}
the var_dump of the $_SESSION will be the following:
array(8) {
[0]=> array(2) { ["product_id"]=> int(4) ["quantity"]=> int(1) }
[1]=> array(2) { ["product_id"]=> int(10) ["quantity"]=> int(1) }
[2]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(2) }
[3]=> array(2) { ["product_id"]=> int(11) ["quantity"]=> int(3) }
[4]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(2) }
[5]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(3) }
[6]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(4) }
[7]=> array(2) { ["product_id"]=> int(12) ["quantity"]=> int(5) } }
Although I add only 4 products: id 4, 10, 11 and 12
function AddToCart($pid, $q){
if(!is_array($_SESSION['products'])){
$_SESSION['products'] = array();
}
foreach($_SESSION['products'] as $key=>$my_value){
if($pid === $my_value['product_id']){
$_SESSION['products'][$key]['quantity'] += $q;
return true;
}
}
$_SESSION['products'][] = array('product_id' => $pid,
'quantity' => $q);
return true;
}
I am using php 5.2.10 i want to do the array_map on the array and i created a function for array mapping
function get_result(){
$result = mysql_query("Select * from table");
while($cr = mysql_fetch_array($result)){
$b = array_map(`calc`,$cr);
$rr_id = $cr['batch_id'].$cr['seq_id'];
$mqrrid = '999'.$rr_id;
$question_id = $cr['question_id'];
foreach ($b as $k => $v){
if(preg_match('{^Item \d+$}',$k)){
$new_insert[] = array(
'r_id'=>$mqrrid,
'q_id' =>$q_id,
'c_id' =>$k,
'rank'=>$v
);
}
}
}
}
function calc($n){
foreach($n as $m=> &$x) {
if (preg_match('{^Item \d+$}', $m)) {
if($x == null){
$x = $x;
}else {
$x = $x - 1;
}
}
}
return $n;
}
I don't know why I cannot call the function calc in array_map.....I cannot figure out the reason.....
Can anyone help me ?
original array :( actually the output after the array_map(calc,$cr) are same as follow)
array(23) {
["batch_id"]=>
string(1) "1"
["seq_id"]=>
string(1) "1"
["question_id"]=>
string(4) "2086"
["Item 1"]=>
string(1) "1"
["Item 2"]=>
string(1) "2"
["Item 3"]=>
string(1) "3"
["Item 4"]=>
string(1) "4"
["Item 5"]=>
string(1) "5"
["Item 6"]=>
NULL
what i need is : (minus the value of Item 1 to 6 by 1, if its null just leave it ~)
array(23) {
["batch_id"]=>
string(1) "1"
["seq_id"]=>
string(1) "1"
["q_id"]=>
string(4) "2086"
["Item 1"]=>
string(1) "0"
["Item 2"]=>
string(1) "1"
["Item 3"]=>
string(1) "2"
["Item 4"]=>
string(1) "3"
["Item 5"]=>
string(1) "4"
["Item 6"]=>
NULL
Finally, the result will become like this:(example of Item 1 and Item 6)
array(4) {
["r_id"]=>
string(5) "99911"
["q_id"]=>
string(4) "2086"
["c_id"]=>
string(6) "Item 1"
["rank"]=>
string(1) "0"
}
array(4) {
["r_id"]=>
string(5) "99916"
["q_id"]=>
string(4) "2086"
["c_id"]=>
string(6) "Item 6"
["rank"]=>
string(4) NULL
}
calc should be global, otherwise it cannot be found. Also, you should pass a string (no ` but rather enclose in ' or ").
Additionally, in general (if you used PHP 5.3), it is better to pass a function reference to the array_map function, instead of a string:
$func = function calc() { ... }
array_map($func, $cr);
I think you don't have to prepare the function for array_map.
function get_result($link_identifier = NULL) {
$result = mysql_query('Select * from table', $link_identifier);
$new = array();
while ($rows = mysql_fetch_assoc($result)) {
$r_id = '999' . $rows['batch_id'] . $rows['seq_id'];
foreach ($rows as $k => $v) {
if ($v !== null && preg_match('#^Item \\d+$#', $k)) {
$v = (string)((int)$v + 1);
}
$new[] = array(
'r_id' => $r_id,
'q_id' => $rows['question_id'],
'c_id' => $k,
'rank' => $v,
);
}
}
return $new;
}