Tree listing for categorys - php

I have an array like this
Array
(
[0] => stdClass Object
(
[cat_id] => 3
[cat_name] => sample 3
[cat_description] =>
[cat_folder] => sample_3
[cat_path] => sample_3
[cat_parent] => 0
[cat_num_files] => 0
[cat_num_files_total] => 0
[cat_user_roles] =>
[cat_owner] => 1
[cat_icon] =>
[cat_exclude_browser] => 0
[cat_order] => 0
)
[1] => stdClass Object
(
[cat_id] => 2
[cat_name] => sample 2
[cat_description] =>
[cat_folder] => sample_2
[cat_path] => sample_3/sample_2
[cat_parent] => 3
[cat_num_files] => 0
[cat_num_files_total] => 0
[cat_user_roles] =>
[cat_owner] => 1
[cat_icon] =>
[cat_exclude_browser] => 0
[cat_order] => 0
)
)
I need to list these like
-sample 3
--sample 2
---sample 4
There is no limit for the link depth, a category may have 5 deep, it may be 10. I have tried this in a foreach loop but failed to retrieve a list like a tree.

I recommend recursion, becouse you don't know how nested it will be. Bellow is example of recursion function.
function genCat($parentCat){
echo $parentCat->name;
if ($parentCat->haveChildren){
foreach($parentCat->children as $child){
genCat($child);
}
}
}
This is just example, hope it helps

Related

Sort an associative array with custom order [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 years ago.
How can we sort an associative array with custom order?
My array look like this
Array
(
[pa_color] => Array
(
[name] => pa_color
[value] =>
[position] => 0
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)
[pa_dimension] => Array
(
[name] => pa_dimension
[value] =>
[position] => 1
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_travel-duration] => Array
(
[name] => pa_travel-duration
[value] =>
[position] => 2
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_travel-type] => Array
(
[name] => pa_travel-type
[value] =>
[position] => 3
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_travelling-with] => Array
(
[name] => pa_travelling-with
[value] =>
[position] => 4
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_volume] => Array
(
[name] => pa_volume
[value] =>
[position] => 5
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_weight] => Array
(
[name] => pa_weight
[value] =>
[position] => 6
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
)
and i want this array is like pa_travel-duration first pa_volume second ?? I know there is a native php function usort but i could not understand this.
This will do the work, but im pretty sure there's much better ways to do it:
Code:
$array = array("pa_color" => "color",
"pa_dimension" => "dimension",
"pa_travel-duration" => "Random Stuff: " . rand(100,999),
"pa_volume" => "volumen"
);
$tmp = array("pa_travel-duration" => $array["pa_travel-duration"],
"pa_volume" => $array["pa_volume"],
);
unset($array["pa_travel-duration"], $array["pa_volume"]);
$array = array_merge($tmp,$array);
print_r($array);
Result:
Array
(
[pa_travel-duration] => Random Stuff: 127
[pa_volume] => volumen
[pa_color] => color
[pa_dimension] => dimension
)
Take care because if the array doesn't have the proper key it will throw an error, you need to add few checks there.
$sort_by = array('pa_travel-duration', 'pa_volume', 'pa_color','pa_dimension','pa_travel-type','pa_travelling-with','pa_weight');
$temp_arr = array();
foreach ($sort_by as $key) {
$temp_arr[$key] = $data[$key];
}
$data = $temp_arr;
echo '<pre>'; print_r($data);
Define your order in $sort_by array

Notice: Undefined index: songtitle. Get value from an array

So I decoded my json, and I get this array out of it
Array (
[totalstreams] => 1
[activestreams] => 1
[currentlisteners] => 0
[peaklisteners] => 2
[maxlisteners] => 100
[uniquelisteners] => 0
[averagetime] => 0
[version] => 2.4.0.147 (posix(linux x64))
[streams] => Array ( [0] => Array (
[id] => 1
[currentlisteners] => 0
[peaklisteners] => 2
[maxlisteners] => 100
[uniquelisteners] => 0
[averagetime] => 0
[servergenre] => Misc
[serverurl] => http://example.com
[servertitle] => Van Den Berg Stream
[songtitle] => Katy Perry - This Is How We Do
[streamhits] => 3
[streamstatus] => 1
[backupstatus] => 0
[streampath] => /stream
[streamuptime] => 1998
[bitrate] => 128
[content] => audio/mpeg ) ) )
I got to this using:
print_r($json)
I'm interested in the songtitle part, so normally I'd go:
$json['streams']['songtitle'];
But it just throws a Undedefined index error.
Do you huys know what I do wrong?
$json['streams'][0]['songtitle'];
That is what you want. Look carefully at your print_r results again, you'll notice the following after streams:
[streams] => Array ( [0] => Array (
You need to take that 0 into account.

PHP Sort Multi-Tired ARRAY by multiple sorts?

i have an php array of sports scores and i want to sort by the following
Wins Desc, Ties Desc, Points Scored Desc, Points Allowed Asc
anyone know how i can do this?
This array was generated by multiple mysql quires
[14] => Array
(
[title] => Crushers
[team_color] => #0000ff
[wins] => 0
[losses] => 1
[ties] => 1
[pointsscored] => 18
[pointsallowed] => 19
)
[15] => Array
(
[title] => Purple Stars
[team_color] => #ae25d9
[wins] => 1
[losses] => 1
[ties] => 0
[pointsscored] => 20
[pointsallowed] => 21
)
[16] => Array
(
[title] => Lighting Boltz
[team_color] => #d6c128
[wins] => 0
[losses] => 0
[ties] => 2
[pointsscored] => 12
[pointsallowed] => 12
)
[17] => Array
(
[title] => The Black Cheetahs
[team_color] => #000000
[wins] => 1
[losses] => 0
[ties] => 1
[pointsscored] => 15
[pointsallowed] => 13
)
I made a function to sort every multidimensional array by one of his columns ,look at array_multisort() and customize this function to your need:
function sortArrayBy($array , $column_name,$sort=SORT_DESC){
foreach ($array as $key => $row) {
$column[$key] = $row[$column_name];
}
array_multisort($column, $sort, $array);
return $array;
}
Call it like this :
<?php sortArrayBy($yourArray,'date') ; ?>

retrieve from array, simple php

I have this:
print_r($response["member"]);
I need to retrieve name under levels, it's at the bottom, how should I write it:
I thought of $response["member"][0]["Sequential"]["levels"]...? Also this number under levels wont be always the same.
Thank you!
Array
(
[0] => Array
(
[ID] => 1
[UserInfo] => Array
(
[ID] => 1
[caps] => Array
(
[administrator] => 1
)
[cap_key] => wp_capabilities
[roles] => Array
(
[0] => administrator
)
[allcaps] => Array
(
[switch_themes] => 1
[edit_themes] => 1
[activate_plugins] => 1
[edit_plugins] => 1
[edit_users] => 1
[edit_files] => 1
[manage_options] => 1
[moderate_comments] => 1
[manage_categories] => 1
[manage_links] => 1
[upload_files] => 1
[import] => 1
[unfiltered_html] => 1
[edit_posts] => 1
[edit_others_posts] => 1
[edit_published_posts] => 1
[publish_posts] => 1
[edit_pages] => 1
[read] => 1
[level_10] => 1
[level_9] => 1
[level_8] => 1
[level_7] => 1
[level_6] => 1
[level_5] => 1
[level_4] => 1
[level_3] => 1
[level_2] => 1
[level_1] => 1
[level_0] => 1
[edit_others_pages] => 1
[edit_published_pages] => 1
[publish_pages] => 1
[delete_pages] => 1
[delete_others_pages] => 1
[delete_published_pages] => 1
[delete_posts] => 1
[delete_others_posts] => 1
[delete_published_posts] => 1
[delete_private_posts] => 1
[edit_private_posts] => 1
[read_private_posts] => 1
[delete_private_pages] => 1
[edit_private_pages] => 1
[read_private_pages] => 1
[delete_users] => 1
[create_users] => 1
[unfiltered_upload] => 1
[edit_dashboard] => 1
[update_plugins] => 1
[delete_plugins] => 1
[install_plugins] => 1
[update_themes] => 1
[install_themes] => 1
[update_core] => 1
[list_users] => 1
[remove_users] => 1
[add_users] => 1
[promote_users] => 1
[edit_theme_options] => 1
[delete_themes] => 1
[export] => 1
[administrator] => 1
)
[filter] =>
[user_login] => admin
[user_nicename] => admin
[user_email] => goranefbl#gmail.com
[user_url] =>
[user_registered] => 2014-01-29 10:57:09
[user_activation_key] =>
[user_status] => 0
[display_name] => admin
[wlm_feed_url] => http://pialarson.com/excel/feed/?wpmfeedkey=1;2e7e48ca65d94e5f0ec1baae46e4972c
[wpm_login_date] => 1392155735
[wpm_login_ip] => 62.68.119.252
)
[Sequential] =>
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
[Cancelled] =>
[CancelDate] =>
[Pending] =>
[UnConfirmed] =>
[Expired] =>
[ExpiryDate] => 1393866766
[SequentialCancelled] =>
[Active] => 1
[Status] => Array
(
[0] => Active
)
[Timestamp] => 1391447566
[TxnID] => WL-1-1391447566
)
)
[PayPerPosts] => Array
(
)
)
)
An answer might be to use array_walk_recursive by following the official documentation:
http://www.php.net/manual/en/function.array-walk-recursive.php
<?php
$properties = new stdClass();
$properties->names = [];
function extractNames($levels, $key, $properties) {
if (
is_object($levels) &&
array_key_exists('Name', get_object_vars($levels)) &&
array_key_exists('Level_ID', get_object_vars($levels))
) {
$properties->names[] = $levels->Name;
}
}
array_walk_recursive($response, 'extractNames', $properties);
echo print_r($properties, true);
<?php
$nameInFirstLevelsElement = current($response["member"][0]["levels"])->Name
?>
This should work to retrieve the Name from the first levels element.
That empty space next to "Sequential" means it doesn't have a value. So that's not the one you're looking for.
Furthermore, one of those levels indicates "stdClass object", which means you can access its members via the -> operator.
Let's strip away everything that doesn't matter for a minute. I think it'll help you understand the data structure:
Array
(
[0] => Array
(
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
)
)
)
)
So this will work:
$object = $response["member"][0]["Levels"][1391447566];
$name = $object->Name;
Edit
If the index of Levels changes every time, then pull it apart a little bit more...
$levels = $response["member"][0]["Levels"];
$firstLevel = array_shift(array_values($levels));
$name = $firstLevel->Name;
See here for a good answer on getting the first element out of the $levels array: https://stackoverflow.com/a/3771228/266374
If the number under the 'Levels' array won't be the same, you can use a foreach to pull out the 'Name' information.
foreach ($response[0]['Levels'] AS $level_key => $level_val) {
$level_name = $level_key->Name;
}
echo 'Name: '.$level_name;
If there is only going to be one element, then it will grab it. If there are multiple numbers under 'Levels', then it will loop through them and assign each one to '$level_name', overwriting any previous assignments. In other words, only the last one it finds will be captured.
EDIT:
In the example, I mistakenly tried to grab the Name from the $key instead of the $val. This is the correct method:
foreach ($response[0]['Levels'] AS $level_key => $level_val) {
$level_name = $level_val->Name;
}
echo 'Name: '.$level_name;
Here is a demo of the working code

How do I retrieve an item from an PHP Object Array?

I want to retrieve quantities from this array.
invoice Object
(
[data:private] => Array
(
[i_status] => pend
[i_title] => 500 HLCoins , 500 HLCoins x8
[i_member] => 1
[i_items] => Array
(
[0] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 1
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[extra] =>
[opt_id] => 0
[associated] =>
[assocBought] =>
[groupRenewals] => 0
[methods] => Array
(
)
[k] => 0
[_tax] => 0
)
[1] => Array
(
[act] => new
[app] => nexus
[type] => product
[cost] => 0
[tax] => 0
[renew_term] => 0
[renew_units] =>
[renew_cost] => 0
[quantity] => 8
[physical] =>
[shipping] => Array
(
)
[weight] => 0
[itemName] => 500 HLCoins
[itemID] => 3
[cfields] => Array
(
)
[opt_id] => 0
[groupRenewals] => 0
[methods] => Array
(
)
[_tax] => 0
)
)
[i_total] => 0
[i_date] => 1347217384
[i_return_uri] =>
[i_paid] => 0
[i_status_extra] => a:1:{s:4:"type";s:4:"zero";}
[i_discount] => 0
[i_temp] =>
[i_ordersteps] => 0
[i_noreminder] => 1
[i_renewal_ids] => Array
(
)
[i_po] =>
[i_notes] =>
[i_shipaddress] =>
[i_id] => 229
)
[takeAction] => 1
)
I've tried a bunch of codes like $invoice->quantity, $invoice[1]->quantity, $this->$invoice->quantity, but none of them seem to display.
It still does not display at all, I tried to print_r and that is the array it gave me.
All the variables are private which means you cannot access them from outside the object. Check out the class definition for the invoice class. There should be some function to get the quantities from the object, or else you could add such a feature to the class.
The whole point of this is separation of concerns. The class may change in the future and possibly not use the same structure, therefore you should use object functions to access the properties, do not access them directly as variables.
You can read more on this subject in the manual or in a book about object-oriented programming.
Seems like all the data is in a private property. You cannot access it from outside directly.
Read the documentation for the class. It should have some method you can call, like getQuantity(), that'll get you the data. It depends on how the class was written and how it is supposed to be used.

Categories