I have a function that returns database results like so:
<?php print_r($homepagematches; ?>
Array
(
[0] => Array
(
[matchid] => 30
[matchtitle] => Testing This!
[matchaverage] => 1
[matchyoutubecode] => New Match
[casterid] => 1
[matchtype] =>
[matchdate] => 2013-05-24 02:19:49
[matchcasteryoutube] => http://youtube.com/huskystarcraft
[matchcaster] => HuskyStarcraft
)
[1] => Array
(
[matchid] => 27
[matchtitle] => Psy vs Camara
[matchaverage] => 1
[matchyoutubecode] => nefC9vkMfG8
[casterid] => 1
[matchtype] =>
[matchdate] => 2013-05-24 02:13:10
[matchcasteryoutube] => http://youtube.com/huskystarcraft
[matchcaster] => HuskyStarcraft
)
The function returns all matches within the last 3 days, What I am trying to figure out is how to reform the array so that I can display the matches under the day in which they were posted. I know a foreach loop is probably required for this, I just can't get my head around the concept I would need to implement.
$matchdate = '';
foreach($this->data['homepagematches'] as $match){
if($matchdate != date('m/d', strtotime($match['matchdate'])) || $matchdate == ''){
$homematch[date('m/d', strtotime($match['matchdate']))] = array(
"matchtitle" => $match['matchtitle']);
}
Basically I need the Array to look like:
Array
(
[05/24] => Array
(
[matchid] =>30
[matchtitle] => Testing This!
[matchyoutubecode] => New Match
[casterid] = 1
)
)
I think this should do it.
foreach($this->data['homepagematches'] as $match){
$tag = date('m/d', strtotime($match['matchdate']));
$data[$tag][] = array(
"matchid" => $match['matchid'],
"matchtitle" => $match['matchtitle'],
"matchyoutubecode" => $match['matchyoutubecode'],
"casterid" => $match['casterid']
);
}
print_r($data);
<?php
$MatchesByDate = array();
foreach($homepagematches as $match) {
list($matchdate,$time) = explode(" ",$match["matchdate"]); //split field into date and time
if( !isset($MatchesByDate[$matchdate]) )
$MatchesByDate[$matchdate] = array(); // If the array for that date doesnt exist yet make it
$MatchesByDate[$matchdate][] = $match; //Use the matchdate as a key and add to the array
}
Related
I need to display a certain object from an array before showing the rest of the array.
The array looks like this:
Array
(
[0] => stdClass Object
(
[template_id] => 91
[template_name] => Alphabet
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821665
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[1] => stdClass Object
(
[template_id] => 92
[template_name] => Blank Template
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821670
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[2] => stdClass Object
(
[template_id] => 31
[template_name] => Holiday Specials
[template_thumbnail] => accommodation-1-20110926.jpg
[template_create_date] => 1456821660
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => Accommodation
[sort] => 3
)
)
I need to show Blank Template first and then show the rest alphabetically (the order it is in now.
Is there a more elegant solution than looping through the array twice? The size of the array can be anything from 1 (the blank template) to countless objects.
$str="";
for($i=0;$i<=count($arr);$i++){
if($arr[$i]['template_name'] == "Blank Template"){
echo $arr[$i]['template_name'];
}else{
$str .= $arr[$i]['template_name']. "<br>";
}
}
echo $str;
Try this:
$firstItem = null;
$outArray = [];
foreach($yourArray as $item){
if($item->template_name == 'Blank Template'){
$firstItem = $item;
}else{
$outArray[$item->template_name] = $item;
}
}
ksort($outArray,SORT_STRING);
array_unshift($outArray,$firstItem);
Just one loop. Pay attention that this way of doing things, just work if you have uniqueness on the template_name!
Hope it helps.
This will work for you, try
<?php
$dataArray = array(0=>array('template_id'=>91,'template_name'=>'Alphabet'),
1=>array('template_id'=>92,'template_name'=>'Blank Template'),
2=>array('template_id'=>31,'template_name'=>'Holiday Specials')
);
$newArray = array();
foreach($dataArray as $key => $val)
{
if(in_array('Blank Template',$val))///find the key for black template
{
unset($dataArray[$key]); ///unset black temp from original array
$newArray[] = $val;///push black temp into new array at 0 index
foreach($dataArray as $k => $v)
{
$newArray[] = $v; ///push the renaming values into new array
}
}
}
echo "<pre>"; print_r($newArray);
?>
This will give you :
Array
(
[0] => Array
(
[template_id] => 92
[template_name] => Blank Template
)
[1] => Array
(
[template_id] => 91
[template_name] => Alphabet
)
[2] => Array
(
[template_id] => 31
[template_name] => Holiday Specials
)
)
LIVE EXAMPLE : CLICK HERE
I am writing a script that collects all the meta data records and generates an array of all the posts and their respective meta data.
Everything seems to work fine except for when I go to push the meta data into the array. Below is the code that I am using and an example of the output that I get. What it is
if (mysql_num_rows($currentCourtMetaGet) != null) {
$metaArray = array();
while($currentCourseMetaArray = mysql_fetch_array($currentCourseMetaGet)){
$metaKey = $currentCourseMetaArray['meta_key'];
$metaValue = $currentCourseMetaArray['meta_value'];
$metaInfo = "$metaKey => $metaValue";
array_push($metaArray, $metaInfo);
}
$currentcourse = array(
"course_name" => $queryOneResultsArray['post_title'],
"course_id" => $queryOneResultsArray['id'],
"course_meta" => $metaArray
);
array_push($courseArray, $currentcourse);
}
Meta Array output:
[course_meta] => Array
(
[0] => licence_code =>
[1] => is_vocable => 0
[2] => region => Gladstone
)
My desired output is this.
[course_meta] => Array
(
licence_code =>
is_vocable => 0
region => Gladstone
)
Can anyone suggest a solution?
You can try this:
if (mysql_num_rows($currentCourtMetaGet) != null) {
$metaArray = array();
while($currentCourseMetaArray = mysql_fetch_array($currentCourseMetaGet)){
$metaKey = $currentCourseMetaArray['meta_key'];
$metaValue = $currentCourseMetaArray['meta_value'];
$metaArray[$metaKey] = $metaValue;
}
$currentcourse = array(
"course_name" => $queryOneResultsArray['post_title'],
"course_id" => $queryOneResultsArray['id'],
"course_meta" => $metaArray
);
array_push($courseArray, $currentcourse);
}
It will output:
[course_meta] => Array
(
[licence_code] =>
[is_vocable] => 0
[region] => Gladstone
)
Arrays are "dumped" in format [key] => value. Unless you output them manualy, the exact format you are trying to achieve is not possible.
Have you tried doing it like this ?
$metaArray[$metakey] = $metaInfo;
There isn't a way to add values with key using associative arrays, what you've created with
$metaInfo = "$metaKey => $metaValue";
is a string variable, which has no key
some time small things in programming get giants. I am working on 2 dimensional array but I am unable to get what I need.
below is my array structure.
Array
(
[0] => Array
(
[0] => 16
[id] => 16
[1] => 1
[userid] => 1
[2] => abc#gmail.com
[email] => abc#gmail.com
[3] => dffsdf
[message] => dffsdf
[4] => 0
[status] => 0
)
[1] => Array
(
[0] => 17
[id] => 17
[1] => 1
[userid] => 1
[2] => xyz#gmail.comnnn
[email] => xyz#gmail.comnnn
[3] => dffsdfnnnnnnnnnnn
[message] => dffsdfnnnnnnnnnnn
[4] => 0
[status] => 0
)
)
what I am doing here is getting the messages for a user with some id. I am doing it like that
if($get_mails[0]['userid'] == $_GET['userid'])
{
$last_key = end(array_keys($get_mails));
echo '{"Messages":[';
foreach($get_mails as $key => $get_each_mail){
$company_name = $get_each_mail['company_name'];
$email_id = $get_each_mail['id'];
$email_body = $get_each_mail['message'];
}
echo '{"CompanyName":"'.$company_name.'","MessageID":"'.$email_id.'","MessageBody":"'.$email_body.'"';
if ($key == $last_key)
{
echo '}]}';
}else{
echo'},';
}
}
what I am unable to do is so funny that I need a loop for [0] in this line of code
if($get_mails[0]['userid'] == $_GET['userid'])
like
if($get_mails[i]['userid'] == $_GET['userid']) and it give me all the records against specific user.
here is what I want to get for a specific user
{"Messages":[{"CompanyName":"newtech","MessageID":"14","MessageBody":"hi how are you"},{"CompanyName":"newtech","MessageID":"15","MessageBody":"hi how are you"},{"CompanyName":"newtech","MessageID":"24","MessageBody":"asfasdfsdfsdfsdfsdfsdfsdfsd"}]}
respose like that, it will add more and more if more records would available against specific user.
Assuming $get_mails contains the Array you posted above (including company_name), you can write something like this:
$output = Array( "Messages" => Array() );
foreach( $get_mails as $k => $arr ) {
$t = Array();
$t['CompanyName'] = $arr['company_name'];
$t['MessageID'] = $arr['id'];
$t['MessageBody'] = $arr['message'];
$output['Messages'][] = $t;
}
echo json_encode( $output );
First you prepare an Array with the structure of your JSON. The syntax $array[] = a will append a to $array. json_encode( ... ) at the end will take care of turning it into valid JSON, even if one of your keys included a quote or other special character that is invalid in JSON.
I believe you only want to display messages from a certain user, and try to accomplish that with if($get_mails[0]['userid'] == $_GET['userid']). I recommend to change your SQL-query to something that accomplishes that, because the performance of your page will greatly increase if you try to crawl through all messages with the following code:
$output = Array( "Messages" => Array() );
foreach( $get_mails as $k => $arr ) {
if( $arr['user_id'] == $_GET['userid'] ) {
$t = Array();
$t['CompanyName'] = $arr['company_name'];
$t['MessageID'] = $arr['id'];
$t['MessageBody'] = $arr['message'];
$output['Messages'][] = $t;
}
}
echo json_encode( $output );
I am using an API and am using a few foreach loops to get to the stage that I am at right now. Please see code below with my comments and also the results that I am getting below that.
// get recent_games api data
$recent_games_data = $player->recent_games();
//start arrays for below
$matches = array();
$gameType = array();
$myData = array();
// using foreach loops to dig in to api data
foreach($recent_games_data['gameStatistics']['array'] as $key_match_data => $value_match_data) {
$matches[] = $value_match_data['statistics'];
}
foreach($matches as $key_match) {
$gameType[] = $key_match['array'];
}
foreach ($gameType as $keyz) {
$myData[] = $keyz;
}
The $mydata array outputs this data below.
Array
(
[0] => Array
(
[0] => Array
(
[statType] => TRUE_DAMAGE_DEALT_TO_CHARACTER
[dataVersion] => 0
[value] => 3351
[futureData] =>
)
[1] => Array
(
[statType] => ASSISTS
[dataVersion] => 0
[value] => 14
[futureData] =>
)
[2] => Array
(
[statType] => NUM_DEATHS
[dataVersion] => 0
[value] => 3
[futureData] =>
)
)
[1] => Array
(
[0] => Array
(
[statType] => TRUE_DAMAGE_DEALT_TO_CHARACTER
[dataVersion] => 0
[value] => 331
[futureData] =>
)
[1] => Array
(
[statType] => ASSISTS
[dataVersion] => 0
[value] => 4
[futureData] =>
)
[2] => Array
(
[statType] => NUM_DEATHS
[dataVersion] => 0
[value] => 7
[futureData] =>
)
)
Of course there is much more data but this is basically what I have now. The first array [0] is each match and the second array are the statistics for that match. What I want is how do I get the statistics of each match without hardcoding the match array number, for example below.
$myData[0][0]['statType']
Let me know if you need more info and thank you.
EDIT: sorry for to mention that as new statistics data gets added to the api, the index number changes. IE TRUE_DAMAGE_DEALT_TO_CHARACTER is [0] to begin with but then may change to [1] or [2] etc.
Consider implementing a class for your stats items after parsing through the data (independent of individual match information keys):
class Stat_Item {
function __construct($id, $info) {
$this->id = $id;
if(!empty($info['damage'])
$this->damage_dealt = $info['damage'];
if(!empty($info['assists']))
$this->assists = $info['assists'];
if(!empty($info['deaths']))
$this->deaths = $info['deaths'];
}
}
$parsed_items = array();
foreach($mydata as $match_id => $match) {
$info = array();
foreach($match as $data_point) {
switch($data_point['statType']) {
case TRUE_DAMAGE_DEALT_TO_CHARACTER:
$info['damage'] = $data_point['value'];
break;
case ASSISTS:
$info['assists'] = $data_point['value'];
break;
case NUM_DEATHS:
$info['deaths'] = $data_point['value'];
break;
}
$parsed_items[] = new Stat_Item($match, $info);
}
}
Other than looping through them all, I don't see any way for you to get a particular match without calling it by its index.
You don't need several foreach loops - you can add to all three arrays in a single one. Also, it looks like $gameType and $myData end up containing the same data.
foreach($recent_games_data['gameStatistics']['array'] as $key_match_data => $value_match_data) {
$matches[] = $value_match_data['statistics'];
$gameType[] = $value_match_data['statistics']['array'];
$myData[] = $value_match_data['statistics']['array'];
}
I don't really understand why you don't just put it into the same array so you can access it easily, though:
foreach($recent_games_data['gameStatistics']['array'] as $key_match_data => $value_match_data) {
$matches[] = array('statistics' => $value_match_data['statistics'], 'data' => $value_match_data['statistics']['array']);
}
I have tried to get the below code to work for a good couple of hours, but just don't succeed.
I have this date array:
Array ( [0] => Array ( [0] => 2007 )
[1] => Array ( [0] => 2008 )
[2] => Array ( [0] => 2009 )
...
)
and this plusMinus one:
Array ( [0] => Array ( [plus] => 2 [date] => 2007 )
[1] => Array ( [minus] => 1 [date] => 2008 )
[2] => Array ( [minus] => 1 [date] => )
[3] => Array ( [plus] => 1 [date] => 2010 [minus] => 1 )
)
I have been trying to combine them into this:
Array ( [0] => Array ( [date] => 2007 [plus]=> 2)
[1] => Array ( [date] => 2008 [minus]=> 1)
[2] => Array ( [date] => 2009 [plusMinus]=> 0)
[3] => Array ( [date] => 2010 [plus] => 1 [minus]=>1 )
...
)
So basically I want to check if a value of the date array exists in the plusMinus array. If true the date and values from the plusMinus array shall replace the entry in the date array.
If false, the original date array entry is complemented by a [plusMinus] => 0 key-value pair.
The way I have tried to do it is this:
foreach ($filler as $key1 => $value1)
{
foreach ($plusMinus as $key2 => $value2)
{
if ($value1['0'] !== $value2['date'])
{
$value1['plusMinus'] = '0';
$result2[$key1][] = $value1;
}
elseif ($value1['0'] == $value2['date'])
{
if (array_key_exists('plus',$value2))
{
$value1['plus'] = $value2['plus'];
$result2[$key1][]=$value1;
}
elseif(array_key_exists('minus',$value2))
{
$value1['minus'] = $value2['minus'];
$result2[$key1][]=$value1;
}
elseif(array_key_exists('minus',$value2) &&
array_key_exists('plus',$value2))
{
}
}
}
}
$valuesComplete = array();
foreach ($result2 as $value) {
$result2 = $value['0'];
array_push($valuesIncomplete, $result2);
}
return $valuesComplete;
Instead of the desired outcome described above I get this:
Array ( [0] => Array
( [0] => 2007 [plus] => 2 )
[1] => Array ( [0] => 2008 [plusMinus => 0 )
[2] => Array ( [0] => 2009 [plusMinus] => 0 )
[3] => Array ( [0] => 2010 [plusMinus] => 0 )
[4] => Array ( [0] => 2011 [plusMinus] => 0 )
[5] => Array ( [0] => 2012 [plusMinus] => 0 )
[6] => Array ( [0] => 2013 [plusMinus] => 0 )
)
What am I missing? Thanks for any help!
Unfortunately, because of the input data format, I can't see any way to do this that doesn't involve an O(n + m + p) operation. But no matter, you gotta do what you gotta do.
Firstly I would start by filtering the useless elements from the PlusMinus array. Since it's already fairly close to the desired output format, it makes sense to use this as the base of the result.
$temp = array();
foreach ($plusMinus as $item) {
if (!empty($item['date'])) {
$temp[$item['date']] = $item;
}
}
Notice that I used the date as the index of the temporary array we're using to build the result. This is to allow you to easily ensure that the result array is in the correct order, and to quickly check whether an item needs to be added from the Filler array.
Next, we need to add any missing elements from the Filler array:
foreach ($filler as $item) {
if (!isset($temp[$item[0]])) {
$temp[$item[0]] = array(
'date' => $item[0],
'plusMinus' => 0
);
}
}
Now all the data is in the array in the correct format, we just need to sort it:
ksort($temp);
...and get convert it back to an indexed array:
return array_values($temp);
No need for the performance killing nested loops or complex flow control.
See it working
As I understood you need to add years that not in second array but in first?
In that case you can do:
foreach ($filler as $key1 => $value1)
{
$ok = false;
foreach ($plusMinus as $key2 => $value2)
{
if($value2['date']==$value1[0])
{
$ok = true;
break;
}
}
if(!$ok)
{
$plusMinus[$value1[0]]=array('date'=>$value1[0], 'plusMinus'=>0);
}
}
<?php
$a1 = array(array( 2007 ),
array( 2008 )
);
$a2 = array(array('plus'=>1, 'date'=>2007),
array('minus'=>1,'date'=>2008),
array('plus'=>1, 'minus'=>1, 'date'=>2008)
);
$r = array();
foreach($a1 as $k1=>$d1) {
$year = $d1[0];
foreach( $a2 as $k2=>$d2 ) {
if( $d2['date'] == $year ) {
$r[$year]['date'] = $year;
if(isset($d2['plus'])) {
$r[$year]['plus'] = $d2['plus'];
}
if(isset($d2['minus'])) {
$r[$year]['minus'] = $d2['minus'];
}
}
}
}
print_r($r);
and result
Array
(
[2007] => Array
(
[date] => 2007
[plus] => 1
)
[2008] => Array
(
[date] => 2008
[minus] => 1
[plus] => 1
)
)
$ar1 = array( array(2007), array(2008), array(2009), array(2010) );
$ar2 = array(
array("date"=>2007, "plus"=>2),
array("date"=>2008, "minus"=>1),
array("date"=>"", "minus"=>1),
array("date"=>2010, "plus"=>1, "minus"=>1)
);
foreach($ar2 as $key=>$val){
if(isset($ar1[$key][0]))
$val["date"] = $ar1[$key][0];
$ar2[$key] = $val;
}
I am not sure if I understand you correctly but this works fine...
It will work only if you are sure that your both arrays "date" equals one to other..
This is what I came up with:
To not create the product of both arrays (foreach inside foreach), I first index the $plusMinus array with the date. That will allow to test quickly if a year exists or not:
$years = array_combine(array_column($plusMinus, 'date'), $plusMinus);
This uses the array_column() function of PHP 5.5, if you don't have it you can easily create it your own.
After doing that it is exactly how you wrote it in your own words:
foreach($date as &$entry)
{
list($year) = $entry;
$entry = array('date' => $year);
// check if a value of the date array exists in the plusMinus array.
if (isset($years[$year])) {
// If true the date and values from the plusMinus array shall replace the entry in the date array
$entry += $years[$year];
} else {
// If false, the original date array entry is complemented by a [plusMinus] => 0 key-value pair.
$entry += array('plusMinus' => 0);
}
}
unset($entry);
See it i action.
This will work just fine.
I did not at all understand your question, but if i got it this is the way:
First make your $datearray more understandable like this:
$dateArray = array(2007,2008,2009,2010);
$plusMinus = array(
array( 'plus' => 2 ,'date' => 2007),
array( 'minus' => 1 ,'date' => 2008),
array ( 'minus' => 1 , 'date' => '' ),
array ( 'plus' => 1 , 'date' => 2010 , 'minus' => 1 )
);
You can make it multidimensional later;
After that:
foreach($dateArray as $k=>$v)
{
if(in_array($v,$plusMinus[$k]))
{
$filler[$k] = $plusMinus[$k];
}
else{
if(empty($plusMinus[$k]['date']))
{
$filler[$k]['date']= $v;
$filler[$k]['plusMinus'] = 0;
}
}
}
This is simple and clean, understandable way with very little code if your arrays will always have the structure you described, meaning the plusMinus values for 2007 are in the cell [0] and the 2007 in the dateArrays is also in the cell [0] like you have shown. I hope i could help.