I have an array that looks like this:
Array
(
[0] => stdClass Object
(
[quiz_id] => 1033
[quiz_venue] => 6
[quiz_host] => 46
[quiz_golden_question] => 100
[quiz_golden_question_outcome] => 0
[quiz_running] => 1
[quiz_status] => 100
[quiz_trainee] => 0
)
[1] => stdClass Object
(
[quiz_id] => 985
[quiz_venue] => 57
[quiz_host] => 21
[quiz_golden_question] => 0
[quiz_golden_question_outcome] => 0
[quiz_running] => 1
[quiz_status] => 310
[quiz_trainee] => 0
)
I want to go through each array, and insert a new value (quiz_venue_name), this is what I have;
$quizzes = $wpdb->get_results( $prepared );
foreach ($quizzes as $quiz => $item) {
$venuetitle = get_the_title($item->quiz_venue);
$quizzes['quiz_venue_name'] = $venuetitle;
}
return $quizzes;
However, all it does is add the new values to the very end of the multidimensional array as new arrays - rather than adding them into each!
I feel like I'm doing something obvious wrong, so any help is much appreciated!
The end result I need would be;
Array
(
[0] => stdClass Object
(
[quiz_id] => 1033
[quiz_venue] => 6
[quiz_host] => 46
[quiz_golden_question] => 100
[quiz_golden_question_outcome] => 0
[quiz_running] => 1
[quiz_status] => 100
[quiz_trainee] => 0
[quiz_venue_name] => NEW VALUE
)
[1] => stdClass Object
(
[quiz_id] => 985
[quiz_venue] => 57
[quiz_host] => 21
[quiz_golden_question] => 0
[quiz_golden_question_outcome] => 0
[quiz_running] => 1
[quiz_status] => 310
[quiz_trainee] => 0
[quiz_venue_name] => NEW VALUE
)
Your $quizzes variable is an array of objects (Instance of stdClass), so you should use it attribute to set value in each iteration ($item->quiz_venue_name instead of $quizzes['quiz_venue_name']):
...
foreach ($quizzes as $quiz => $item) {
$venuetitle = get_the_title($item->quiz_venue);
$item->quiz_venue_name = $venuetitle;
}
...
In fact the $quizzes['quiz_venue_name']=... code will be set a value for index quiz_venue_name in root of $quizzes array.
Related
I have a following ModulePermissions Array
Array
(
[0] => Array
(
[module_permission_index_id] => 347
[module_id] => 1
[user_id] => 29
[can_view] => 1
[can_edit] => 1
[can_add] => 1
)
[1] => Array
(
[module_permission_index_id] => 348
[module_id] => 2
[user_id] => 29
[can_view] => 1
[can_edit] => 1
[can_add] => 1
)
... ... ...
)
Target:
Now I want to get Array to be sorted based on their module (module Id has multiple permissions)
something like below (please ignore syntax and get the idea)
[1] => array(
array(
[module_permission_index_id] => 347
[user_id] => 29
[can_view] => 1
[can_edit] => 1
[can_add] => 1
)
)
[2] => array(
array(
[module_permission_index_id] => 348
[user_id] => 29
[can_view] => 1
[can_edit] => 1
[can_add] => 1
)
)
... ... ...
)
Is there any way PHP helps do this?
Simplest way is:
$newData = [];
foreach ($yourData as $item) {
$newData[$item['module_id']][] = $item;
}
I have used below query to get array result with id as key value,
$this->db->select('gp.id, gp.lot_no, SUM(gb.weight) AS weight, SUM(gb.staple) AS staple, SUM(gb.mic) AS mic, SUM(gb.strength) AS strength, SUM(gb.trash) AS trash, gb.color_grade');
$this->db->from(GIN_BALES . ' gb');
$this->db->join(GIN_PROCESS . ' gp', 'gp.id=gb.process_id');
$this->db->where('gb.sold_status', 0);
$this->db->where('gp.ginner_id', $this->prscr_id);
$this->db->where('gp.program', $program_id);
$this->db->group_by('gp.id');
$lot_details = $this->db->get()->result();
But I getting the array result like below and array key have 0,1.I want that array key with id like,561,562.
Array
(
[0] => stdClass Object
(
[id] => 561
[lot_no] => 1
[weight] => 16230
[staple] => 3600
[mic] => 0
[strength] => 0
[trash] => 0
[color_grade] => 0
)
[1] => stdClass Object
(
[id] => 562
[lot_no] => 2
[weight] => 15523
[staple] => 3600
[mic] => 0
[strength] => 0
[trash] => 0
[color_grade] => 0
)
)
Can anyone provide solution for this query issue?
Here is one liner,
// null will take id as key and whole array as value
$temp = array_column($temp, null, "id");
Reference: array_column.
Demo.
Output:
Array
(
[561] => stdClass Object
(
[id] => 561
[lot_no] => 1
[weight] => 16230
[staple] => 3600
[mic] => 0
[strength] => 0
[trash] => 0
[color_grade] => 0
)
[562] => stdClass Object
(
[id] => 562
[lot_no] => 2
[weight] => 15523
[staple] => 3600
[mic] => 0
[strength] => 0
[trash] => 0
[color_grade] => 0
)
)
i want to check condition before for loop execution
this is my array
$rs=Array (
[0] => Array (
[questionID] => 47
[surveyID] => 51
[userID] => 31
[question_Title] => Choose Any One?
[question_Type] => Dropdown
[response] => 1.Android 2.Windows 3.Blackberry
[required] => 0
[add_time] => 0
)
[1] => Array (
[questionID] => 48
[surveyID] => 51
[userID] => 31
[question_Title] => Is it?
[question_Type] => Bigbox
[response] => Yes No
[required] => 1
[add_time] => 0
)
[2] => Array (
[questionID] => 129
[surveyID] => 51
[userID] => 31
[question_Title] => sELECT
[question_Type] => Single
[response] => DFG HBK GHCK HK
[required] => 0
[add_time] => 0
)
)
now i want to check if in $rs [required] => 1
then stop over all execution or $rs traversing using for each loop
rather from above example i want to stop executing first loop also.
Use array_column and achieve this functionality
Reference
http://php.net/manual/en/function.array-column.php
http://php.net/manual/en/function.array-search.php
Lower version array column function code
https://github.com/ramsey/array_column/blob/master/src/array_column.php
<?php
//assumed records is your array
$required = array_column($records, 'required');
if(FALSE===array_search('1', $required))
{
//value is not exist then process your loop
}
else
{
//required value is 1 then ignore the loop
}
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 a set of nested arrays.
[data] is the top level array.
The lower level arrays are all identified by incremental numbers, dynamically assigned...essentially each sub-array identifies a row/record of information.
How would I extract the count of the sub-arrays? I need to be able to do this to post this data into a DB.
The number of sub-arrays is dynamic, and can change depending on what data I am parsing through.
[data] => Array
(
[0] => Array
(
[id] => 3475
[name] => Player1
[score] => 11870
[rank] => 213
[total_cities] => 2
[crown] => None
[alliance_id] => 134
[title] => Earl
[fame_total] => 509875
[fame_rank] => 381
[defeated_total] => 3436
[defeated_rank] => 376
[plunder_total] => 1388754
[plunder_rank] => 245
)
[1] => Array
(
[id] => 3523
[name] => Player2
[score] => 1978
[rank] => 281
[total_cities] => 1
[crown] => None
[alliance_id] => 134
[title] => Baron
[fame_total] => 0
[fame_rank] => 448
[defeated_total] => 0
[defeated_rank] => 448
[plunder_total] => 0
[plunder_rank] => 436
)
[2] => Array
(
[id] => 73
[name] => Player3
[score] => 1308
[rank] => 304
[total_cities] => 1
[crown] => None
[alliance_id] => 134
[title] => Marquess
[fame_total] => 5604153
[fame_rank] => 237
[defeated_total] => 37270
[defeated_rank] => 229
[plunder_total] => 68130
[plunder_rank] => 335
)
I used a combination of the methods highlighted by Marc B and Thanos to get my desired result
This is the code I used:
$count = 0;
foreach($data as $data=>$inner_array){
$count = $count+1;
}
echo $count;
I ran it with a test data set with 143 unique rows, and I got that echo back, so life is good.
Thanks guys.
Simplest method:
$count = 0;
foreach($mainarray as $subarray)
$count += count($subarray);
}
Let's assume $data is your main array:
This one prints the name of each inner array (0, 1, 2... for your example) and then counts each sub-array items:
echo "Number of sub-arrays: ".count($online_time); //optional
foreach($data as $inner_array=>$data_of_inner_array) {
echo $inner_array;
echo " --- ".count($data_of_inner_array);
echo "<br/>";
}
i assume output will be
Number of sub-arrays: 3
0 --- 14
1 --- 14
2 --- 14