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
Related
I have collection of array and i want delete array of array where "answer_id" key is not exits.
my array look like this.
Array
(
[0] => Array
(
[question_no] => 1
[subject_id] => 1
[question_id] => 255
[currect_ans_id] => 2657
[time_taken] => 110
[is_visited] => 1
[is_saved] => 0
[answer_id] => 2659
)
[1] => Array
(
[question_no] => 2
[subject_id] => 1
[question_id] => 256
[currect_ans_id] => 2662
[time_taken] => 0
[is_visited] => 1
[is_saved] => 0
)
)
and want array like this(where answer_id key exits).
Array
(
[0] => Array
(
[question_no] => 1
[subject_id] => 1
[question_id] => 255
[currect_ans_id] => 2657
[time_taken] => 110
[is_visited] => 1
[is_saved] => 0
[answer_id] => 2659
)
)
You can use array_filter to remove entries which don't have an answer_id:
$output = array_filter($input, function ($a) { return isset($a['answer_id']); });
Demo on 3v4l.org
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
How to compare 2 strings alphabetically in PHP?
(5 answers)
Closed 5 years ago.
I have an array called "$myarray", which looks like this:
[0] => Array
(
[PrinterID] => 4
[PrinterName] => PRT04_GL
[UserID] => 1
[isDefaultPrinter] => 0
[isMapped] => 0
)
[1] => Array
(
[PrinterID] => 1
[PrinterName] => PRT01_Zentral
[UserID] =>
[isDefaultPrinter] => 0
[isMapped] => 0
)
[2] => Array
(
[PrinterID] => 2
[PrinterName] => PRT02_BH
[UserID] =>
[isDefaultPrinter] => 0
[isMapped] => 0
)
[3] => Array
(
[PrinterID] => 3
[PrinterName] => PRT03_EDV
[UserID] =>
[isDefaultPrinter] => 0
[isMapped] => 1
)
I want to sort the data by ["PrinterName"]. The wanted result would be:
[0] => Array
(
[PrinterID] => 1
[PrinterName] => PRT01_Zentral
[UserID] =>
[isDefaultPrinter] => 0
[isMapped] => 0
)
[1] => Array
(
[PrinterID] => 2
[PrinterName] => PRT02_BH
[UserID] =>
[isDefaultPrinter] => 0
[isMapped] => 0
)
[2] => Array
(
[PrinterID] => 3
[PrinterName] => PRT03_EDV
[UserID] =>
[isDefaultPrinter] => 0
[isMapped] => 1
)
[3] => Array
(
[PrinterID] => 4
[PrinterName] => PRT04_GL
[UserID] => 1
[isDefaultPrinter] => 0
[isMapped] => 0
)
Based on this example I tried the following:
uasort($myarray, 'sort_by_order');
function sort_by_order ($a, $b) {
return $a['PrinterName'] - $b['PrinterName'];
}
This does not work. I get errors like "A non-numeric value encountered ...", of course because my values are strings and the function is for numeric values.
How do I sort the array?
Thank you!
EDIT:
I think I did find the solution here. I used this and it seems to work:
uasort($myarray, 'sort_by_order');
function sort_by_order ( $a, $b ) { return strcmp($a['PrinterName'], $b['PrinterName']); }
Please try with $a['PrinterName'] > $b['PrinterName']
It will compare the values
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
I have started working with Magento, and I'm trying to get all custom options associated with a given product.
I've found a solution to that, however, I ran into issues.
My PHP-code:
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
It sure do return the correct information. Atleast in the first iteration:
[2] => Array
(
[id] => 2
[type] => drop_down
[title] => Custom option 1
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
)
)
However, during the second iteration (and perhaps even the third and forth and so on), I'm having duplicates of the values. In the second iteration, I'm getting the same values as i got in the first iteration PLUS the correct values for the second iteration:
[1] => Array
(
[id] => 1
[type] => drop_down
[title] => Custom option 2
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
[1] => Array
(
[option_type_id] => 1
[option_id] => 1
[title] => Flaphack 1.1
)
[2] => Array
(
[option_type_id] => 2
[option_id] => 1
[title] => Flaphack 1.2
)
[3] => Array
(
[option_type_id] => 3
[option_id] => 1
[title] => Flaphack 1.3
)
)
)
Do you guys have any idea what's going on? Would be greatly appriciated.
Best,
Nikolaj
Try this code,
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
$valuesArray = array(); // added line
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
The $valuesArray is getting values in each iteration and you never cleared it. So when the outer foreach gets into second loop the $valuesArray gets values in incremental fashion. If you clear $valuesArray in each iteration of outer foreach you will get what you wanted.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
sorting array based on inner-array key-value
Array (
[0] => Array (
[id] => 2
[name] => 4
[closed] =>
[date] => 1319625994
[votes_up] => 0
[votes_down] => 0
[votes_pct_up] => 0
[votes_pct_down] => 0
[votes_balance] => 0
[votes_total] => 0 )
[1] => Array (
[id] => 3
[name] => 3
[closed] =>
[date] => 1319625994
[votes_up] => 0
[votes_down] => 0
[votes_pct_up] => 0
[votes_pct_down] => 0
[votes_balance] => 0
[votes_total] => 0 )
[2] => Array (
[id] => 4
[name] => 2
[closed] =>
[date] => 1319625995
[votes_up] => 1
[votes_down] => 0
[votes_pct_up] => 100
[votes_pct_down] => 0
[votes_balance] => 1
[votes_total] => 1 )
[3] => Array (
[id] => 1
[name] => 1
[closed] =>
[date] => 1319623450
[votes_up] => 2
[votes_down] => 0
[votes_pct_up] => 100
[votes_pct_down] => 0
[votes_balance] => 2
[votes_total] => 2 )
)
How do i sort these according to their [votes_balance] value?
Use the usort function of PHP with something like this:
function compare($a, $b) {
if($a['id'] == $b['id']) return 0;
return ($a['id'] < $b['id']) -1 : 1;
}