Okay here is my recursion algo:
public function getCategoryTree($tree,$return = array()) {
foreach ($tree->children as $child) {
if (count($child->children) > 0 )
$return[$tree->name] = $this->getCategoryTree($child, $return);
else
$return[] = $child->name;
}
return $return;
}
Here is a snippet of the data structure I'm trying to traverse
Object(stdClass)#290 (6) {
["category_id"]=>
int(1)
["parent_id"]=>
int(0)
["name"]=>
string(4) "Root"
["position"]=>
int(0)
["level"]=>
int(0)
["children"]=>
array(2) {
[0]=>
object(stdClass)#571 (7) {
["category_id"]=>
int(2)
["parent_id"]=>
int(1)
["name"]=>
string(18) "Root MySite.com"
["is_active"]=>
int(0)
["position"]=>
int(0)
["level"]=>
int(1)
["children"]=>
array(11) {
[0]=>
object(stdClass)#570 (7) {
["category_id"]=>
int(15)
["parent_id"]=>
int(2)
["name"]=>
string(9) "Widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(2)
["children"]=>
array(19) {
[0]=>
object(stdClass)#566 (7) {
["category_id"]=>
int(24)
["parent_id"]=>
int(15)
["name"]=>
string(16) "Blue widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(3)
["children"]=>
array(0) {
}
}
<snip....>
I'm trying to get a php data structure like such
categories = array( "Root" =>
array("Root MySite.com" =>
array( "Widgets" =>
// final element is NOT an array
array ("Blue Widgets", "Purple Widgets" ...)
)
)
)
I can't quite seem to get the data structure i'm looking for using my recursive algo. Any help
would be great.
Eventually I'll need to parse it again on the frontend and display it, but another problem for another day...
Have a look at this phpFiddle for a full working example. The only error I found was the $this->getCategoryTree which gave me an Fatal Error Using $this when not in object context. So are you sure the function is within the correct scope?
Updated
I hope this one works. :)
function traverse($root, $return = array()) {
$return[$root->name] = array();
foreach ($root->children as $child) {
if (count($child->children) > 0) {
traverse($child, &$return[$root->name]);
}else {
array_push(&$return[$root->name], $child->name);
}
}
return $return;
}
The output from this is:
Array ( [Root] =>
Array (
[Root MySite.com] =>
Array (
[Widgets] => Array ( [0] => Blue Widget [1] => Purple Widget)
[Gizmos] => Array ( [0] => Blue Gizmos [1] => Purple Gizmos)
)
[FooBar.com] =>
Array (
[Widgets] => Array ( [0] => Blue Widget [1] => Purple Widget)
[Gizmos] => Array ( [0] => Blue Gizmos [1] => Purple Gizmos)
)
)
)
Again, full working example
Related
I have an array like bellow
Array
(
[0] => Array
(
[parent_id] => 0
[child_id] => 1
[uuid] => a707aa7f-2180-4cb5-9227-57c948491731
[sdi] =>
[serial] => 03466720000004033
[gs1_id] => urn:epc:id:sscc:0346672.0000004033
[type] => CONTAINER
)
[1] => Array
(
[parent_id] => 1
[child_id] => 2
[uuid] => 5bd9da67-90eb-4fb1-b25a-0f534efd661f
[sdi] => SDI-5bd9da67-90eb-4fb1-b25a-0f534efd661f
[serial] => 100000003718
[gs1_id] => urn:epc:id:sgtin:0369499.232915.100000003718
[type] => PRODUCT
)
[2] => Array
(
[parent_id] => 2
[child_id] => 3
[uuid] => b3224592-0268-4853-8700-03f53e759fa1
[sdi] => SDI-b3224592-0268-4853-8700-03f53e759fa1
[serial] => 100000042535
[gs1_id] => urn:epc:id:sgtin:0369499.032915.100000042535
[type] => PRODUCT
)
)
but I need a tree structure data from the array by using parent_id and child_id and the array size may be 100,000.
How can I do that?
Write a recursive function in order to convert the array from linear to tree. I have written such a function for your use-case.
Look at the following code:
/**
* Recursively sort an array of hierarchically. Childs will be placed under a 'children' member of their parent term.
*/
function sort_array_hierarchically(Array &$linear, Array &$into, $parentId = 0) {
foreach ($linear as $i => $elem) {
if ($elem["parent_id"] == $parentId) {
array_push($into,$elem);
}
}
foreach ($into as $k => $topElem) {
$into[$k]["children"] = [];
sort_array_hierarchically($linear, $into[$k]["children"], $topElem["child_id"]);
}
}
$linear_array = [
["parent_id"=>0,"child_id"=>1,"name"=>"foo"],
["parent_id"=>1,"child_id"=>2,"name"=>"bar"],
["parent_id"=>0,"child_id"=>3,"name"=>"lol"],
["parent_id"=>1,"child_id"=>4,"name"=>"sure"],
["parent_id"=>4,"child_id"=>5,"name"=>"never"],
["parent_id"=>3,"child_id"=>6,"name"=>"never"]
];
$into = [];
sort_array_hierarchically($linear_array,$into);
var_dump($into);
The output looks like this:
array(2) {
[0]=>
array(4) {
["parent_id"]=>
int(0)
["child_id"]=>
int(1)
["name"]=>
string(3) "foo"
["children"]=>
array(2) {
[0]=>
array(4) {
["parent_id"]=>
int(1)
["child_id"]=>
int(2)
["name"]=>
string(3) "bar"
["children"]=>
array(0) {
}
}
[1]=>
array(4) {
["parent_id"]=>
int(1)
["child_id"]=>
int(4)
["name"]=>
string(4) "sure"
["children"]=>
array(1) {
[0]=>
array(4) {
["parent_id"]=>
int(4)
["child_id"]=>
int(5)
["name"]=>
string(5) "never"
["children"]=>
array(0) {
}
}
}
}
}
}
[1]=>
array(4) {
["parent_id"]=>
int(0)
["child_id"]=>
int(3)
["name"]=>
string(3) "lol"
["children"]=>
array(1) {
[0]=>
array(4) {
["parent_id"]=>
int(3)
["child_id"]=>
int(6)
["name"]=>
string(5) "never"
["children"]=>
array(0) {
}
}
}
}
}
For some reasons, when I try to do an if for $value['is_set'] == false, I get undefined index error, however, if I do an isset($value['is_set']) I get 1
I did a print_r and got the ff:
Array ( [is_set] => [product] => Array ( [product_ID] => 1 [product_name] => Insulated Terminal Lugs 1.25 - 3Y [product_code] => [unit_ID] => 80 [unit_name] => pc(s) [price] => 50 [qty] => 1 [discount] => 0 [subtotal] => 50 [amount] => 50 ) [set] => Array ( [set_ID] => [set_items] => Array ( [0] => Array ( [amount] => 0 ) ) [amount] => 0 ) [selectedProduct] => Array ( [ID] => 1 [product_name] => Insulated Terminal Lugs 1.25 - 3Y [product_code] => [price] => 50 ) [selectedUnit] => Array ( [ID] => 80 [option_key] => pc(s) ) [amount] => 50 )
why is this happening?
here is my code:
public function create($model, $value, $datetime, $transaction_type, $notes) {
if (($model->general_status == Sales::GEN_STATUS_OPEN || $model->general_status == Sales::GEN_STATUS_CLOSED) && ($model->delivery_status == Sales::DELIVERY_STATUS_DELIVERED)) {
$pth = new ProductTransactionHistory();
//var_dump($value); exit();
if ($value['is_set'] == false) {
$pth->generateSales($transaction_type, $datetime, '(add)', $model, $value, Yii::$app->user->id, $notes);
$pth->stock_in_out = ProductTransactionHistory::STOCK_OUT;
//$pth->save();
$this->saveDebug($pth);
}
}
this function is called by the following code:
$so = Json::decode($request['purchase-orders']);
foreach ($so['orders'] as $key => $value) {
$order->create($model, $value, $datetime);
}
the full var_dump of $so is
array(8) { ["orders"]=> array(2) { [0]=> array(6) { ["is_set"]=> bool(false) ["product"]=> array(10) { ["product_ID"]=> string(1) "1" ["product_name"]=> string(33) "Insulated Terminal Lugs 1.25 - 3Y" ["product_code"]=> string(0) "" ["unit_ID"]=> string(2) "80" ["unit_name"]=> string(5) "pc(s)" ["price"]=> string(2) "50" ["qty"]=> int(1) ["discount"]=> int(0) ["subtotal"]=> int(50) ["amount"]=> int(50) } ["set"]=> array(3) { ["set_ID"]=> bool(false) ["set_items"]=> array(1) { [0]=> array(1) { ["amount"]=> int(0) } } ["amount"]=> int(0) } ["selectedProduct"]=> array(4) { ["ID"]=> string(1) "1" ["product_name"]=> string(33) "Insulated Terminal Lugs 1.25 - 3Y" ["product_code"]=> string(0) "" ["price"]=> string(2) "50" } ["selectedUnit"]=> array(2) { ["ID"]=> string(2) "80" ["option_key"]=> string(5) "pc(s)" } ["amount"]=> int(50) } [1]=> array(5) { ["is_set"]=> bool(true) ["product"]=> array(3) { ["unit_ID"]=> string(0) "" ["unit_name"]=> string(0) "" ["amount"]=> int(0) } ["set"]=> array(3) { ["set_ID"]=> string(1) "1" ["set_items"]=> array(2) { [0]=> array(10) { ["product_ID"]=> int(4) ["product_name"]=> string(33) "Power Miniature Solder Relay 220v" ["product_code"]=> string(5) "LY4NJ" ["unit_ID"]=> int(80) ["unit_name"]=> string(5) "pc(s)" ["qty"]=> int(1) ["price"]=> int(200) ["discount"]=> int(0) ["subtotal"]=> int(200) ["amount"]=> int(200) } [1]=> array(10) { ["product_ID"]=> int(5) ["product_name"]=> string(26) "Relay Socket 14A for LY4NJ" ["product_code"]=> string(6) "PYF14A" ["unit_ID"]=> int(80) ["unit_name"]=> string(5) "pc(s)" ["qty"]=> int(1) ["price"]=> int(20) ["discount"]=> int(0) ["subtotal"]=> int(20) ["amount"]=> int(20) } } ["amount"]=> int(220) } ["selectedSet"]=> array(3) { ["ID"]=> string(1) "1" ["set_name"]=> string(20) "LY4NJ 220v w/ Socket" ["price"]=> string(3) "220" } ["amount"]=> int(220) } } ["has_downpayment"]=> bool(false) ["payment_type"]=> string(4) "cash" ["grandTotal"]=> int(270) ["generalStatus"]=> string(6) "closed" ["statusText"]=> string(6) "Cancel" ["cssStatus"]=> string(14) "btn btn-danger" ["showPayment"]=> bool(false) }
the full error is:
PHP Notice – yii\base\ErrorException
Undefined index: is_set
also this is related to this issue:
Why does accessing array index on boolean value does not raise any kind of error?
but I don't know how to get pass this without using array...
Initially I tried empty($value['is_set']) as an alternative, but it didn't work and I freaked out. I reconsidered that option again and found that it works! I don't know why it didn't work earlier. Thanks for all your support!
I have an array like this :
$lessonOptions=array();
$lessonOptions[0]=array("Physics","6.00","2015-01-01","-","4");
$lessonOptions[1]=array("Physics","16.00","2015-01-01","-","2");
$lessonOptions[2]=array("Maths","10.00","2015-07-01","-","10");
$lessonOptions[3]=array("Maths","20.00","2015-07-01","-","10");
I want to create an output with new array called optionarray which contains:
**
physics 6.00 2015-01-04 -
physics 16.00 2015-01-01 -
maths 10.00 2015-07-01 -
maths 20.00 2015-07-07 -
My problem is that I can see every line of maths but only one line of physics is missing .
How can I display all line ?
My actual code is :
$lessonGroup=$lessonOptions[0][0];
$display=FALSE;
$state=0;
$nbLessons=count($lessonsOptions);
for ($i = 0; $i<$nbLessons; $i++)
{
if ($i+1!=$nbLessons) $lessonGroupSuivant=$lessonOptions[$i+1][0];
else $display=TRUE;
switch ($state)
{
case 0 :
$infoLesson[$state]=$lessonOptions[$i];
default :
{
if ($lessonGroup==$lessonGroupSuivant)
{
$infoLesson[$state]=$lessonOptions[$i];
$state=$state+1;
}
else
{
$display=TRUE;
$lessonGroup=$lessonGroupSuivant;
$state=0;
}
}
}
if ($display==TRUE)
{
//var_dump($infoLesson);
$display=FALSE;
}
}
My actual array (wrong)
As you can see, the size of my array is 1 , I need to have 2 because I have two field for the lesson physics.
array(1) { [0]=> array(5) { [0]=> string(31) "physics" [1]=> string(10) "6.00" [2]=> string(10) "2015-01-01" [3]=> string(1) "-" [4]=> float(42) } }
array(2) { [0]=> array(5) { [0]=> string(15) "Maths" [1]=> string(11) "10.00" [2]=> string(10) "2015-07-01" [3]=> string(1) "-" [4]=> float(10) } [1]=> array(5) { [0]=> string(15) "Maths" [1]=> string(11) "10.00" [2]=> string(10) "2015-07-12" [3]=> string(1) "-" [4]=> float(10) } }
Okay i think i found what you need:
<?php
$lessonOptions=array();
$lessonOptions[0]=array("Physics","6.00","2015-01-01","-","4");
$lessonOptions[1]=array("Physics","16.00","2015-01-01","-","2");
$lessonOptions[2]=array("Maths","10.00","2015-07-01","-","10");
$lessonOptions[3]=array("Maths","20.00","2015-07-01","-","10");
$optionarray = array();
$lastLessonKey = '';
$i = 0;
foreach ($lessonOptions as $key => $data) {
if (empty($lastLessonKey)) {
$lastLessonKey = $data[0];
} else if ($lastLessonKey !== $data[0]) {
$i++;
$lastLessonKey = $data[0];
}
$optionarray[$i][] = $data;
}
var_dump($optionarray);
Output:
array(2) { [0]=> array(2) { [0]=> array(5) { [0]=> string(7) "Physics" [1]=> string(4) "6.00" [2]=> string(10) "2015-01-01" [3]=> string(1) "-" [4]=> string(1) "4" } [1]=> array(5) { [0]=> string(7) "Physics" [1]=> string(5) "16.00" [2]=> string(10) "2015-01-01" [3]=> string(1) "-" [4]=> string(1) "2" } } [1]=> array(2) { [0]=> array(5) { [0]=> string(5) "Maths" [1]=> string(5) "10.00" [2]=> string(10) "2015-07-01" [3]=> string(1) "-" [4]=> string(2) "10" } [1]=> array(5) { [0]=> string(5) "Maths" [1]=> string(5) "20.00" [2]=> string(10) "2015-07-01" [3]=> string(1) "-" [4]=> string(2) "10" } } }
So, you are willing to group arrays by some value
$infoLesson = array();
foreach ($lessonOptions as $v) {
$infoLesson[$v[0]][] = $v;
}
You can then retrieve arrays by key.
For example printing $infoLesson['Maths'] will get you
Array
(
[0] => Array
(
[0] => Maths
[1] => 10.00
[2] => 2015-07-01
[3] => -
[4] => 10
)
[1] => Array
(
[0] => Maths
[1] => 20.00
[2] => 2015-07-01
[3] => -
[4] => 10
)
)
And $infoLesson['Physics']
Array
(
[0] => Array
(
[0] => Physics
[1] => 6.00
[2] => 2015-01-01
[3] => -
[4] => 4
)
[1] => Array
(
[0] => Physics
[1] => 16.00
[2] => 2015-01-01
[3] => -
[4] => 2
)
)
Im trying to remove a session['cart_items] array from a multi array and I can't seem to get the delete part to work.
I'm getting the id through: $_POST['product] however I've tried the following and getting a bit stuck:
$temp = array_flip($_SESSION['cart_items']);
unset($_SESSION['cart_items'][$temp[$_POST['product']]]);
I've also tried:
unset($_SESSION['cart_items'][$key]);
My output is:
Array
(
[0] => Array
(
[0] => Array
(
[item_id] => 407
[item_name] => Am I Bothered? About Homophobia
[item_qty] => 22
)
)
)
An help would be great
Multiple array result:
array(1) {
["cart_items"]=>
array(2) {
[1]=>
array(1) {
[0]=>
array(3) {
["item_id"]=>
string(3) "407"
["item_name"]=>
string(31) "Am I Bothered? About Homophobia"
["item_qty"]=>
string(2) "50"
}
}
[2]=>
array(1) {
[0]=>
array(3) {
["item_id"]=>
string(4) "1131"
["item_name"]=>
string(50) "10 Ways A Condom Can’t Protect You – Postcards"
["item_qty"]=>
string(2) "14"
}
}
}
}
for(i=0;i<sizeof($_SESSION['cart_items'][0]);i++){
if($_SESSION['cart_items'][0][i]['item_id'] == $key);
unset($_SESSION['cart_items'][0][i]['item_id']);
}
in fear of duplicating content, i have looked through so many similar SO questions, but i think i need a bit more than code, to tell me how solve my problem- would be lovely with some explaination too.
How do i turn $list:
array(4) {
[0]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
[1]=>
array(2) {
["title"]=>
string(6) "Zarafa"
["id"]=>
int(34)
}
[2]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
[3]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
}
Into $list:
array(2) {
[0]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
[1]=>
array(2) {
["title"]=>
string(6) "Zarafa"
["id"]=>
int(34)
}
}
By removing duplicate entries?
Use array_unique() with SORT_REGULAR flag.
$new_array = array_unique($array, SORT_REGULAR);
Output should be:
Array
(
[0] => Array
(
[title] => Zambezia
[id] => 31
)
[1] => Array
(
[title] => Zarafa
[id] => 34
)
)
Demo.