PHP Looping an array and running a function on a array item - php

I seem to get this issue a few times and figure it out then the next time I come across it I can't figure it out.
So I have a SQL statement which returns to a $result variable as usual...
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
I will show you a slimmed down return below
Array
(
[eid] => 1
[eTitle] => premier league
[eDesc] =>
[cid] => 1
[deleted] => 0
[eStartTime] => 15:00
[eHome] => 1
[eAway] => 2
[eKickoff] => 15:00:00
[eDate] => 2016-08-20
)
Array
(
[eid] => 2
[eTitle] => fa cup
[eDesc] =>
[cid] => 1
[deleted] => 0
[eStartTime] => 15:00
[eHome] => 1
[eAway] => 2
[eKickoff] => 15:00:00
[eDate] => 2016-08-27
)
Now what i want to do is loop through the $result and on each key eHome and eAway run a function below is the pseudo code for what I am trying to do.
loop ( $reult )
$row[eHome][eHomeData] = $this->getTeam( $row['eHome'] )
$row[eHome][eAwayData] = $this->getTeam( $row['eAway'] )
So basically I want to rebuild the array with the home or away team data which uses the id given in eHome and eAway.
Should I do it like this or should I be using JOINS in MySQL?
Sorry if I have worded this badly I having been struggling for a few hours with this and gave up.
Thanks in advance guys.
Tom

This is what I have used in the end guys sorry for the poorly worded question. Is there a better way to do this, here is the code and then the print_r() dump for you to see where I was going with this.
$stmt = $this->conn->prepare('
SELECT * from events WHERE cid = :cid
');
$stmt->bindParam( ':cid', $categoryid, PDO::PARAM_INT );
if( $stmt->execute() )
{
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$resultCount = count($result);
for( $i = 0; $i < $resultCount; $i++ ) {
$result[$i]['homeTeamData'] = $this->getTeam( $result[$i]['eHome'] );
$result[$i]['awayTeamData'] = $this->getTeam( $result[$i]['eAway'] );
}
}
Below is the print_r() which adds an extra awayTeamData and homeTeamData with the data collected in the loop added above
Array
(
[0] => Array
(
[eid] => 1
[eTitle] => premier league
[eDesc] =>
[cid] => 1
[deleted] => 0
[eStartTime] => 15:00
[eHome] => 1
[eAway] => 2
[eKickoff] => 15:00:00
[eDate] => 2016-08-20
[homeTeamData] => Array
(
[tid] => 1
[tName] => Chelsea
[deleted] => 0
)
[awayTeamData] => Array
(
[tid] => 2
[tName] => Man Utd
[deleted] => 0
)
)
[1] => Array
(
[eid] => 2
[eTitle] => fa cup
[eDesc] =>
[cid] => 1
[deleted] => 0
[eStartTime] => 15:00
[eHome] => 1
[eAway] => 2
[eKickoff] => 15:00:00
[eDate] => 2016-08-27
[homeTeamData] => Array
(
[tid] => 1
[tName] => Chelsea
[deleted] => 0
)
[awayTeamData] => Array
(
[tid] => 2
[tName] => Man Utd
[deleted] => 0
)
)
)

Related

search inside arrays with condition in php

I have an api with a list of arrays inside one array and each array inside this array it has one key [attributes] and inside this key one array with key [CITY_NAME]
this is my array coming from api
this array number is 0 but every day this number is changed and my figures come wrong, what is the good way to always have my city figures using the key [CITY_NAME]
I am fetching the data using this code
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$data = $json_data['features'];
$mycity = $data[0]['attributes'];
Array
(
[0] => Array
(
[attributes] => Array
(
[CITY_NAME] => city1
[Name] => city1
[ADMIN_NAME] => city1
[POP_CLASS] => 5,000,000 to10,000,000
[Population] => 7676654
[Population_Data_Source] => Wikipedia
[Population_Data_Date] => 2018
[CityID] => 14
[Longitude] => 46.7614868685786
[Latitude] => 24.7388786516234
[Confirmed] => 0
[Recovered] => 0
[Deaths] => 0
[Active] => 0
[Tested] => 0
[Name_Eng] => city1
[Join_Count] => 61
[Confirmed_SUM] => 5152
[Deaths_SUM] => 9
[Recovered_SUM] => 1407
[Active_SUM] => 3736
[Tested_SUM] => 376607
[ObjectId] => 14
)
)
[1] => Array
(
[attributes] => Array
(
[CITY_NAME] => city2
[Name] => city2
[ADMIN_NAME] => city2
[POP_CLASS] => 1,000,000 to 5,000,000
[Population] => 1675368
[Population_Data_Source] => Wikipedia
[Population_Data_Date] => 2010
[CityID] => 9
[Longitude] => 39.8148987363852
[Latitude] => 21.4273876500039
[Confirmed] => 0
[Recovered] => 0
[Deaths] => 0
[Active] => 0
[Tested] => 0
[Name_Eng] => city2
[Join_Count] => 59
[Confirmed_SUM] => 6848
[Deaths_SUM] => 85
[Recovered_SUM] => 1145
[Active_SUM] => 5618
[Tested_SUM] => 0
[ObjectId] => 9
)
)
Since I may have misunderstood and you may have many, just build a new array with CITY_NAME:
foreach($data as $values) {
$result[$values['attributes']['CITY_NAME']] = $values['attributes'];
}
Now you can access by CITY_NAME:
echo $result['city1']['Population'];
This might be easier. Extract all attributes from all arrays into an array, then create an array from that indexed by CITY_NAME:
$data = array_column(array_column($json_data['features'], 'attributes'),
null, 'CITY_NAME');

Delete Multidimensional Array Item By Values In the Item

Hey guys I have this array :
Array
(
[qty] => 1
[id] => 2
[name] => sallate me gjera plot
[price] => 8
[category_id] => 25
[dish_name] => sallate me gjera plot
[dish_id] => 2
[dish_category_id] => 25
[dish_qty] => 1
[dish_price] => 8
)
Array
(
[qty] => 1
[id] => 1
[name] => sallate cezar
[price] => 12
[category_id] => 25
[dish_name] => sallate cezar
[dish_id] => 1
[dish_category_id] => 25
[dish_qty] => 1
[dish_price] => 12
)
And what I'm trying to do is to unset the item by dish_id.
This is the way I intend to do that :
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
foreach ($_SESSION["cart_products"] as $key =>$cart_itm)
{
if($cart_itm["dish_id"]==$removable_id)
{
unset($cart_itm[$key]);
}
}
}
Can anyone tell me what I'm doing worng..thanks :D
Actually you need to unset data from actual array which is $_SESSION["cart_products"] not $cart_itm.
So change unset($cart_itm[$key]); to unset($_SESSION["cart_products"][$key])
As alternative, you can use array_filter() with an anonimous function:
$removable_id = 1;
$_SESSION["cart_products"] = array_filter
(
$_SESSION["cart_products"],
function( $row ) use( $removable_id )
{
return $row['dish_id'] != $removable_id;
}
);
print_r( $_SESSION["cart_products"] );
will print:
Array
(
[0] => Array
(
[qty] => 1
[id] => 2
[name] => sallate me gjera plot
[price] => 8
[category_id] => 25
[dish_name] => sallate me gjera plot
[dish_id] => 2
[dish_category_id] => 25
[dish_qty] => 1
[dish_price] => 8
)
)

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

php merging arrays

In the multidimensional array below, I would like to merge arrays that have the same merge_id. I'm not sure "merge" is the right word: in the example below, array['0'] should become array['0'] with in it array['0']['0'] and array['0']['1'], the latter being equal to array['1']. I hope this makes sense ...
The array comes out of the db sorted on merge_id so arrays with matching merge_id are always "next to" each other, and there will only ever be 2 with the same merge_id
As I loop through the array I know I need to keep a variable that is always equal to the previous merge_id and if there is a match between previous and current, then merge.
Array
(
[0] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 3
[fee] => 111
[year] => 2009
[quarter] => 3
[date_inserted] => 1264948583
[description] => 2009 - Q3
[fee_type] =>
[merge_id] => a87ff679a2f3e71d9181a67b7542122c
[total_paid] => 0
[total_remainder] => 0
)
[1] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 6
[fee] => 55.5
[year] => 2010
[quarter] => 2
[date_inserted] => 1264949470
[description] => 2010 - Q2
[fee_type] =>
[merge_id] => a87ff679a2f3e71d9181a67b7542122c
[total_paid] => 0
[total_remainder] => 0
)
[2] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 4
[fee] => 111
[year] => 2009
[quarter] => 4
[date_inserted] => 1264948583
[description] => 2009 - Q4
[fee_type] =>
[merge_id] =>
[total_paid] => 0
[total_remainder] => 0
)
[3] => Array
(
[client_id] => 5
[company_name] => company111_name
[id] => 7
[fee] => 55.5
[year] => 2010
[quarter] => 3
[date_inserted] => 1264949470
[description] => 2010 - Q3
[fee_type] =>
[merge_id] =>
[total_paid] => 0
[total_remainder] => 0
)
)
Code
$merger = $data['search']['0']['merge_id'];
$i = 0;
foreach($data['search'] as $fee)
{
if($fee['merge_id'] == $merger)
{
//bump up & merge arrays
???
}
$merger = $fee['merge_id'];
$i++;
}
You can use the ID as key to put all items with the same ID in the same array:
$merged = array();
foreach ($data['search'] as $fee) {
if ($fee['merge_id'] == '') {
continue;
}
if (!isset($merged[$fee['merge_id']])) {
$merged[$fee['merge_id']] = array();
}
$merged[$fee['merge_id']][] = $fee;
}
$merged = array_values($merged);
Notice that this will skip the items with an empty merge ID. You could also use a default merge ID in that case by replacing continue; with $fee['merge_id'] = 0;.
foreach($array as $p)
$result[$p['merge_id']][] = $p;

Categories