Two dimensional PHP array not outputting correctly - php

I have the following array of dates and places - basically each date will need to allow for multiple places. I am trying to display the array below into something like the following format:
20140411
Basingstoke
Salisbury
20140405
Basingstoke
20140419
Salisbury
... and so on
The array:
Array
(
[20140411] => Array
(
[0] => Array
(
[0] => Basingstoke
)
[1] => Array
(
[0] => Salisbury
)
)
[20140405] => Array
(
[0] => Array
(
[0] => Basingstoke
)
)
[20140419] => Array
(
[0] => Array
(
[0] => Salisbury
)
)
[20140427] => Array
(
[0] => Array
(
[0] => Basingstoke
)
)
)
I believe I'm close, but I have always had some sort of mental block when it comes to working with arrays/keys etc. I am trying to do a nested foreach loop, which displays the dates fine, but am just getting "Array" outputted for the locations:
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venue) {
echo $venue;
}
}
Can someone spot where I'm going wrong here?
EDIT:
Here is where the arrays are being created, if that helps?
$dates = array();
while ( have_rows('course_date') ) : the_row();
$theVenue = get_sub_field('venue');
// Use the date as key to ensure values are unique
$dates[get_sub_field('date')][] = array(
$theVenue->post_title
);
endwhile;

In your case venue is an array.
It's always an array with the only element you can address as [0].
Thus...
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venue) {
echo $venue[0];
}
}
Or, in case you can have multiple venues in that last-level array, you can re-write the inner foreach adding another one:
foreach ($dates as $date => $dateKey) {
// Format the date
$theDate = DateTime::createFromFormat('Ymd', $date);
$theFormattedDate = $theDate->format('d-m-Y');
echo '<h4>'.$theFormattedDate.'</h4>';
foreach ($dateKey as $key => $venues) {
foreach($venues as $v) {
echo $v;
}
}
}

Places are nested 1 level deeper, you need one more foreach.
Never mind, that other guy said this plugin is supposed to work like that :)

Related

unable to set array values in two php foreach loops

I have defined two arrays as
$array1 = (8,10);
Array2 was array of stdobjects which was later converted into below using json decode, encode. Php echo output of the same is below:
$array2 = Array
(
[0] => Array
(
[id] => 6
)
[1] => Array
(
[id] => 8
)
[2] => Array
(
[id] => 10
)
)
Later I created one array
foreach( $array2 as $value )
{
$valuesArray[] = array('',$value['id'],Input::get('date'),'0');
}
What I am trying to do is compare array1 with valuesarray. If $value['id'] i.e. second element matches with any of the element in array1, I will save 4th element of $nnn as 1. If it doesnt match with any of the element, I will save it as 0.
My code below:
foreach ($valuesArray as $value2)
{
foreach ($array1 as $value1)
{
if ($value2[1] == $value1)
{$x = 1;}
else
{$x = 0;}
}
$nnn[] = "('','".$value2[1]."','".Input::get('date')."','".$x."')";
}
echo '<pre>',print_r($nnn,1),'</pre>';
The output that I am getting is:
Array
(
[0] => ('','6','2016-04-25','0')
[1] => ('','8','2016-04-25','0')
[2] => ('','10','2016-04-25','1')
)
Correct output should be:
Array
(
[0] => ('','6','2016-04-25','1')
[1] => ('','8','2016-04-25','1')
[2] => ('','10','2016-04-25','0')
)
try this:
$nnn = array();
foreach ($valuesArray as $value) {
$x = (in_array($value[1], $array1))?1:0;
$nnn[] = "('','".$value[1]."','".Input::get('date')."','{$x}')";
}

Build SQL query from multiple arrays - PHP

I've got an array that looks like this..
Array
(
[fm] => Array
(
[133.74] => Array
(
[base] => Array
(
[0] => 2015-09-29
[1] => 2015-09-30
)
)
[202.59] => Array
(
[base] => Array
(
[0] => 2015-10-01
)
)
)
[fmtax] => Array
(
[13.51] => Array
(
[0] => 2015-09-29
[1] => 2015-09-30
)
[20.46] => Array
(
[0] => 2015-10-01
)
)
)
and I need to build a SQL statement to insert the relevant values. I'm thinking it will need to be a unique query for each array item.
So I'll end up needing something like
$sql = "insert into mytable ('price', 'tax', 'date')
values ('133.74', '13.51', '2015-09-29')";
What I've got so far is this...
foreach ($sale['fm'] as $key => $value) {
$i=0;
$g=count($value['base']);
while($i < $g) {
echo($sale['fm'][$key]['base'][$i]."<br />");
$i++;
}
}
which does well for the "fm" key - but I'm getting hung up on how to grab the value from the second associated "fmtax" array key. I was thinking using something like current/next as it iterates through...but am kinda scratching my head on it.
I am assuming that fm and fmtax both have same number of elements and the order of related elements (price and tax) from fm and fmtax are same. What you can do is - store the taxes from fmtax with simple keys in this way :
$taxes = array();
$c = 0;
foreach ($sale['fmtax'] as $key => $value) {
$taxes[$c] = $key;
$c++;
}
Then you can access this new $taxes array from your own code block in this way :
$c = 0;
foreach ($sale['fm'] as $key => $value) {
//Here you have the related tax
$tax = $taxes[$c];
$i=0;
$g=count($value['base']);
while($i < $g) {
echo($sale['fm'][$key]['base'][$i]."<br />");
$i++;
}
$c++;
}

Array values replaced rather than pushed

I'm trying to build a multidimensional array like array(years => array(months)). Each new month added to a year replaces the old month value in the year array rather than appending the value.
<?php
$dates = array();
foreach (Blog::all() as $blog) {
$date_year = date("Y", strtotime($blog->created_at));
$date_month = date("F", strtotime($blog->created_at));
if (!in_array($date_year, $dates)) {
$dates[$date_year] = array();
}
if (!in_array($date_month, $dates[$date_year])) {
$dates[$date_year][] = $date_month;
print $date_year." ".$date_month."<br>";
}
}
print_r($dates); ?>
Outputs:
Array ( [2009] => Array ( [0] => December ) [2010] => Array ( [0] => March ) [2011] => Array ( [0] => August ) [2012] => Array ( [0] => November ) [2013] => Array ( [0] => October ) [2014] => Array ( [0] => April ) )
The months displayed are the last month available for each year. I have also tried with array_push($dates[$date_year], $date_month) for the same result.
The year array is being overwritten each time here:
if (!in_array($date_year, $dates)) {
$dates[$date_year] = array();
}
Check the array keys instead of the array values with array_key_exists:
if (!array_key_exists($date_year, $dates)) {
$dates[$date_year] = array();
}
Or, better yet IMO, use isset as suggested by vp_arth below. (For succintness.)
if (!isset($dates[$date_year])) {
$dates[$date_year] = array();
}

Getting multi dimensional array to create new arrays based on index value

I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here

multi array usage in foreach loop

I've got the following array stored in a $_SESSION
[Bookings] => Array
(
[date] => Array
(
[0] => 1/12/2013
[1] => 1/19/2013
[2] => 2/03/2013
)
[price] => Array
(
[0] => 100
[1] => 150
[2] => 120
)
)
However I want to use a foreach loop and perform calculation on both values within the array.I can't seem to fugure out how I can use the foreach to accomodate multivalues, I've got a sample of a foreach I wrote below of what I'm trying to achieve. Anyone point me in the right direction.
foreach ($_SESSION['Bookings'] as $bookings)
{
myDate = $bookings[date];
myPrice = $bookings[price];
// Some other stuff here
}
foreach ($_SESSION['Bookings']['date'] as $key => $value) {
$myDate = $value;
$myPrice = $_SESSION['Bookings']['price'][$key];
}
simpler I guess :)
foreach (array_keys($_SESSION['Bookings']['date']) as $key)
{
$myDate = $_SESSION['Bookings']['date'][$key];
$myPrice = $_SESSION['Bookings']['price'][$key];
}
Should work?
Some info on: array_keys
just loop through on of your subarrays and read the corresponding value from the other
foreach ( $_SESSION['Bookings'][ 'date' ] as $key => $myDate) {
$myPrice = $_SESSION['Bookings'][ 'price' ][ $key ];
// here you can access to $myDate and $myPrice
// Some other stuff here
}

Categories