I am using Codeigniter Sessions to build a "Betslip".
I am adding the team name and odds to the bet slip and then plan to loop through each "bet" element to create a betslip.
The ideal array needs to look like :
[betslip] => Array
(
[bet] => Array
(
[team] => Rayo Vallecano
[odds] => 67/100
)
[bet] => Array
(
[team] => Elche
[odds] => 1/100
)
)
However in my code, I just seem to be overwriting what is already there.
My current PHP code is as follows :
// Get Team Name
$teamname = $this->uri->segment(3);
// Get Odds
$odds1 = $this->uri->segment(4);
$odds2 = $this->uri->segment(5);
$odds = $odds1;
$odds .= "/";
$odds .= $odds2;
// Build An array titled Bet
$bet = array(
'bet' => array(
'team' => urldecode($teamname),
'odds' => $odds
)
);
$betslip = $this->session->userdata('betslip');
// Create The Betslip For The First Time...
if(empty($betslip))
{
$this->session->set_userdata('betslip', $bet);
}
else
{
// Add To The Betslip Array...
$betslip['bet'] = array(
'team' => urldecode($teamname),
'odds' => $odds
);
$this->session->set_userdata('betslip', $betslip);
}
How do I just append a bet to the existing bet slip array?
Is it possible to have multiple array keys with the same name too?
Thanks in advance..
This is not an ideal array
[betslip] => Array
(
[bet] => Array
(
[team] => Rayo Vallecano
[odds] => 67/100
)
[bet] => Array
(
[team] => Elche
[odds] => 1/100
)
)
it should be like
[betslip] => Array
(
[0] => Array
(
[team] => Rayo Vallecano
[odds] => 67/100
)
[1] => Array
(
[team] => Elche
[odds] => 1/100
)
)
<?php
$item = array();
$item2 = array(
'team' => 1,
'odds' => "1/100"
);
for ($x = 0; $x <= 10; $x++) {
$item[] = $item2;
}
print_r($item);
?>
Related
1.fetching the values from a same table with different date
<?php
$date= date("Y-m-d");;
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
$data_yest = array(); // create a variable to hold the information
while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
$data_yest[] = $row_yest; // add the row in to the results (data) array
}
print_r($data_yest);
$result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
$data_today = array(); // create a variable to hold the information
while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
$data_today[] = $row_today; // add the row in to the results (data) array
}
print_r($data_today);
exit;
?>
2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp
Array (
[0] => Array ( [isp] => aol [sent_yest] => 46838 )
[1] => Array ( [isp] => gmail [sent_yest] => 33015 )
[2] => Array ( [isp] => juno [sent_yest] => 93544 )
[3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
[4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)
Array (
[0] => Array ( [isp] => aol [sent_today] => 14135 )
[1] => Array ( [isp] => att [sent_today] => 624 )
[2] => Array ( [isp] => gmail [sent_today] => 21263 )
[3] => Array ( [isp] => juno [sent_today] => 74934 )
[4] => Array ( [isp] => roadrunner [sent_today] => 939 )
[5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)
Now i need a result like this isp name, yesterday's sent count, today's sent count
[isp, sent_yest, sent_today],
[aol, 46838, 14135],
[att, 0, 624],
[gmail, 33015, 21263],
Anyone help me to solve this.. Thanks in advance
Do it like below:-
$final_array = array();
if(count($arr1)>=count($arr2)){
foreach ($arr1 as $arr){
$key='';
foreach ($arr2 as $ar2){
if($arr['isp'] == $ar2['isp']){
$final_array[$arr['isp']] = array($arr['isp'],$arr['sent_yest'],$ar2['sent_today']);
$key ='';break;
}else{
$key = $arr['isp'];
}
}
if($key!==''){
$final_array[$key] = array($arr['isp'],$arr['sent_yest'],0);
$key ='';
}
}
}
if(count($arr2)>count($arr1)){
foreach ($arr2 as $ar2){
$key='';
foreach ($arr1 as $arr){
if($ar2['isp'] == $arr['isp']){
$final_array[$ar2['isp']] = array($ar2['isp'],$arr['sent_yest'],$ar2['sent_today']);
$key ='';break;
}else{
$key = $ar2['isp'];
}
}
if($key!==''){
$final_array[$key] = array($ar2['isp'],0,$ar2['sent_today']);
$key ='';
}
}
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/814625
I would avoid foreach if it's possible, since it leads to code that's much harder to understand. With array operation it can look like this:
// First we merge the two arrays
$merged = array_merge($data_yest, $data_today);
// Then format it
$final = array_reduce($merged, function($final, $item) {
// Initialize for each isp if it's not present
// This way we avoid overwriting previous data and have a default value 0
if (! isset($final[ $item['isp'] ])) {
$final[ $item['isp'] ] = [
'sent_yest' => 0,
'sent_today' => 0,
];
}
// And if one of the days is present, we add it
if (isset($item['sent_yest'])) {
$final[ $item['isp'] ][ 'sent_yest' ] = $item['sent_yest'];
}
if (isset($item['sent_today'])) {
$final[ $item['isp'] ][ 'sent_today' ] = $item['sent_today'];
}
// Then return the modified array
return $final;
}, []);
print_r($final);
exit;
Result looks like this:
Array
(
[aol] => Array
(
[sent_yest] => 46838
[sent_today] => 14135
)
[gmail] => Array
(
[sent_yest] => 33015
[sent_today] => 21263
)
[juno] => Array
(
[sent_yest] => 93544
[sent_today] => 74934
)
[roadrunner] => Array
(
[sent_yest] => 6181
[sent_today] => 939
)
[yahoo] => Array
(
[sent_yest] => 71444
[sent_today] => 22059
)
[att] => Array
(
[sent_yest] => 0
[sent_today] => 624
)
)
I've received and XML, converted it into an array for usage.
The XML comes in unpredictable multi dimension when I convert it into array.
Had been looking around but could not find a suitable solution.
An alternative is to simplify the converted array.
I've converted an XML to array in PHP, and the result looked like this:
Array
(
[GetMLCBRes] => Array
(
[0] => Array
(
[Ord] => Array
(
[0] => Array
(
[OrdId] => Array
(
[0] => DP Order ID
)
)
)
[ReqInf] => Array
(
[0] => Array
(
[ReqDat] => Array
(
[0] => Date of Request
)
)
)
[Res] => Array
(
[0] => PDF Report
)
)
)
)
May I know how to drop the index like [0] but remain the assoc keys like [Ord], [OrdId], [ReqInf] and [Res], etc.
How to convert it to become like this?
Array
(
[GetMLCBRes] => Array
(
[Ord] => Array
(
[OrdId] => DP Order ID
)
[ReqInf] => Array
(
[ReqDat] => Date of Request
)
[Res] => PDF Report
)
)
it works but if you change your structure maybe it won't. It's not optimized too :)
$input = Array(
'GetMLCBRes' => Array(Array(
'Ord' => Array(Array(
'OrdId' => Array('DP Order ID')
)),
'ReqInf' => Array(Array(
'ReqDat' => Array('Date of Request')
)),
'Res' => Array('PDF Report')
))
);
foreach($input as &$in){
$sub = $in[0];
foreach($sub as $key => &$value){
$sub2 = $value[0];
if(!is_array($sub2)){
$sub[$key] = $sub2;
continue;
}
$final2 = array();
foreach($sub2 as $key2 => $final)
$final2[$key2] = $final[0];
$sub[$key] = $final2;
}
$in = $sub;
}
var_dump($input);
You can test it here : http://sandbox.onlinephpfunctions.com/code/a6770c7649d7d277aa1dc3544093cc87bed0951d
This should work as expected :
function recursive_skip(array $ary) {
foreach($ary as $k => &$v) {
if (is_array($v)) {
// Skip it
$v = $v[0];
}
if (is_array($v)) {
// If current array item is an array itself, recursively call the function on it
$v = recursive_skip($v);
}
}
// Return updated array to calling context
return $ary;
}
$source = Array(
'GetMLCBRes' => Array(Array(
'Ord' => Array(Array(
'OrdId' => Array('DP Order ID')
)),
'ReqInf' => Array(Array(
'ReqDat' => Array('Date of Request')
)),
'Res' => Array('PDF Report')
))
);
$dest = recursive_skip($source);
var_dump($dest);
A few caveats : the function will only skip one array level each time (but could be adapted to handle more if needed) and might come with a significant performance cost if your source array is huge since it's recursive (O(n)), it just walks through the whole array tree.
i have been troubling to format array correctly
i have this code:
require('simple_html_dom.php');
$table = array();
$html = file_get_html('apc.html');
foreach($html->find('tr') as $row) {
$rack = ltrim($row->find('td',0)->plaintext);
$location = ltrim($row->find('td',1)->plaintext);
$usage = ltrim($row->find('td',2)->plaintext);
$auk = ltrim($row->find('td',3)->plaintext);
$cost = ltrim($row->find('td',4)->plaintext);
$rack = rtrim($rack);
$location = rtrim($location);
$usage = rtrim($usage);
$auk = rtrim($auk);
$cost = rtrim($cost);
$table[$rack][$usage][$auk][$cost] = true;
}
echo '<pre>';
print_r($table);
echo '</pre>';
using simple_html_dom above i can convert html table to an array as follow:
[Rack01] => Array
(
[741,60] => Array
(
[1.409,04] => Array
(
[267,72] => 1
)
)
[110,88] => Array
(
[210,67] => Array
(
[40,03] => 1
)
)
)
[Rack 09] => Array
(
[843,84] => Array
(
[1.603,30] => Array
(
[304,63] => 1
)
)
)
I would like to have result as below:
array(
[0] => array (
[usage] => 'Rack 01',
[usage] => '741,60',
[auk] => '1.409.04',
[cost] => '267,72')
[1] => array (
[usage] => 'Rack 02',
[usage] => 'value???',
[auk] => 'value???',
[cost] => 'value???')
any help would be apreaciate
Something like this. Also note that trim will do both left and right:
foreach($html->find('tr') as $row) {
$rack = trim($row->find('td',0)->plaintext);
$location = trim($row->find('td',1)->plaintext);
$usage = trim($row->find('td',2)->plaintext);
$auk = trim($row->find('td',3)->plaintext);
$cost = trim($row->find('td',4)->plaintext);
$table[] = array('rack' => $rack,
'usage' => $usage,
'auk' => $auk,
'cost' => $cost);
}
I have arrays like this.
[11] => Array
(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 6/1/2011
[!time] => 2:27 PM
[!] => 2011-06-01T14:27:00-07:00
)
[smi_cchistoryid] => {678C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
[12] => Array
(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 5/1/2011
[!time] => 2:27 PM
[!] => 2011-05-01T14:27:00-07:00
)
[smi_cchistoryid] => {688C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
How can i group them by location id then by smi_processingmonth
So I get something like this
[1134 Hooksett Rd] => Array
(
[ 5/1/2011] = array(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 5/1/2011
[!time] => 2:27 PM
[!] => 2011-05-01T14:27:00-07:00
)
[smi_cchistoryid] => {688C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
[1/1/2011] = array(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 6/1/2011
[!time] => 2:27 PM
[!] => 2011-06-01T14:27:00-07:00
)
[smi_cchistoryid] => {678C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
)
I have tried
foreach($array as $keys)
{
$key = $keys['smi_processingmonth']['!date'];;
if (!isset($groups[$key]))
{
$groups[$key] = array($keys);
} else {
$groups[$key][] = $keys;
}
}
$newGroups = array();
if(is_array($groups))
{
foreach($groups as $cats => $values)
{
foreach($values as $itemValues){
$st = rtrim(trim($itemValues['smi_locationid']['!']));
$key = $st;
if (!isset($newGroups[$key]))
{
$newGroups[$key] = array($groups);
} else {
$newGroups[$key][] = $itemValues;
}
}
}
}
Thanks!
Taking from Johan with a few modifications:
avoid ltrim if already using trim
put in a function, I can use temporary variables to maintain readability
add a final [], to avoid nasty $name/$date collision, out of original request, but safer
function compactArray($data)
{
$new_structure = array();
foreach ( $data as $row )
{
$name = trim($row['smi_locationid']['!name']);
$date = trim($row['smi_processingmonth']['!date']);
$new_structure[ $name ][ $date ][] = $row;
}
return $new_structure;
}
Ehm, i have not tested it. But isn't it just:
$new_structure = array();
foreach ( $data as $row ) {
$key1 = rtrim(trim($row['smi_locationid']['!name']));
$key2 = rtrim(trim($row['smi_processingmonth']['!date']));
$new_structure[$key1][$key2] = $row;
}
This code could use some isset()s, but i decided to keep them out for clarity.
The following produces your desired output array, correctly sorted:
function transaction_datecmp($tran1, $tran2)
{
return strtotime($tran1['smi_processingmonth']['!']) -
strtotime($tran2['smi_processingmonth']['!']);
}
$output_arr = array();
foreach ($input_arr as $transaction) {
$location = $transaction['smi_locationid'] ['!name'];
$date = $transaction['smi_processingmonth']['!date'];
$output_arr[$location][$date] = $transaction;
}
ksort($output_arr); // sorts by location
foreach ($output_arr as &$transaction_arr) {
uasort($transaction_arr, 'transaction_datecmp');
}
Your data structure relies on the assumption that there cannot be two transactions on the same day, which is a somewhat dangerous assumption. Also using a location as a key is far from ideal (because of spelling, location changes, etc.) - unless it really should group things, like for paper mailing.
Data cleanup, like trimming strings, should be done beforehand, ideally at data input time.
I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.