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
}
Related
Array
(
[data] => Array
(
[0] => Array
(
['degree_level'] => Bachelor's
)
[1] => Array
(
['field_of_study'] => Science
)
[2] => Array
(
['grade_point'] => 3
)
[3] => Array
(
['criteria'] => desired
)
)
)
What I want :
Array
(
[data] => Array
(
['degree_level'] => Bachelor's
['field_of_study'] => Science
['grade_point'] => 3
['criteria'] => desired
)
)
You should use array_flatten(); to achieve your goal like this,
$flattened = array_flatten(Your_Data_Array);
Please give it a try and let me know.
UPDATE
$flattened = array_map(function($item) {
return $item[0];
}, Your_Data_Array);
For more information you can visit this for PHP functions.
Let me know in case of any queries.
$output = array_map(function($item) { return $item[0]; }, $myArray);
Try this,
foreach($data as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$new_array[$key2] = $val2;
}
}
You can do it by loop.
foreach ($data as $key => $value) {
foreach ($value as $key1 => $value2) {
$data[$key1] = $value2;
}
}
You could use for example a double foreach loop to use the key and the value from the second loop and add those to the $arrays["data"] array.
Then you could use unset to remove the nested arrays.
$arrays = [
"data" => [
["degree_level" => " Bachelor's"],
["field_of_study" => "Science"],
["grade_point" => 3],
["criteria" => "desired"]
]
];
foreach($arrays["data"] as $dataKey => $data) {
foreach ($data as $key => $value) {
$arrays["data"][$key] = $value;
}
unset($arrays["data"][$dataKey]);
}
print_r($arrays);
That would give you:
Array
(
[data] => Array
(
[degree_level] => Bachelor's
[field_of_study] => Science
[grade_point] => 3
[criteria] => desired
)
)
Demo
you can achieve this using array_collapse.
Link
EDIT :
while tag has changed.
Here is the core php solution based on Laravel array_collapse:
function collapse($array)
{
$results = [];
foreach ($array as $values) {
if (! is_array($values)) {
continue;
}
$results = array_merge($results, $values);
}
return $results;
}
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++;
}
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
My question is maybe repetitive but I really find it hard. (I have read related topics)
This is the array :
Array
(
[0] => Array
(
[legend] => 38440
)
[1] => Array
(
[bestw] => 9765
)
[2] => Array
(
[fiuna] => 38779
)
[3] => Array
(
[adam] => 39011
)
[4] => Array
(
[adam] => 39011
)
[5] => Array
(
[adam] => 39011
)
)
I have tried many ways to handle this array and find out the most common value. The result I expect is "adam"
$countwin = array_count_values($winnernames);
$maxwin = max($countwin);
$mostwinner = array_keys($countswin, $maxwin);
EDIT : My array is like this array("A"=>"1" , "B"=>"2" , "A"=>"1") it should return A is the most common
How about iterating your array and counting the values you've got?
$occurences = array();
foreach ($data as $row) {
foreach ($row as $key => $score) {
if (empty($occurences[$key])) {
$occurences[$key] = 1;
} else {
$occurences[$key]++;
}
}
}
and then sorting that
arsort($occurences);
and grabbing the first element of the sorted array
$t = array_keys($occurences);
$winner = array_shift($occurences);
You may try this code. A brute force method indeed. But a quick search made me to find this an useful one:
function findDuplicates($data,$dupval) {
$nb= 0;
foreach($data as $key => $val)
if ($val==$dupval) $nb++;
return $nb;
}
EDIT : Sorry, I misinterpreted your question! But it might be the first hint of finding the one with maximum counter.
I don't have a problem, but i'm looking for any other maybe better or faster solution.
I have array with two keys ALL and ART:
$myData = Array (
[ALL] => Array (
[0] => Array (
[ID_COUNTRY] => 23
[DELIVERY_DAYS] => 23
[AMOUNT] => 23
)
[1] => Array (
[ID_COUNTRY] => 30
[DELIVERY_DAYS] => 30
[AMOUNT] => 30
)
)
[ART] => Array (
[0] => Array (
[ID_COUNTRY] => 10
[DELIVERY_DAYS] => 10
[AMOUNT] => 10
)
[1] => Array (
[ID_COUNTRY] => 2
[DELIVERY_DAYS] => 20
[AMOUNT] => 20
)
)
)
And have 2 foreach loops to check the values
<?php
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
...
}
}
?>
Is possible to do something like this or is the only solution to use two foreach loops without any additional libraries.
<?php
foreach($myData as $key1=>$key2=>$value) {
echo $key1; // [ALL] or [ART]
echo $key2; // [ALL][$key2] or [ART][$key2];
}
?>
If you want to loop over your multi-dimensional array you need your provided code:
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
...
}
}
No way around it without using something that would in the end do this too. There is no speed to be gained here. And if there is it would be a micro-optimization that you should ignore :)
It's not possible. But you could do it as
<?php
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
echo $key1;
echo $key2;
}
}
?>
Perhaps not exactly what you are looking for; I still wanted to notify you of it though. You can recursively loop through a multidimensional array, using a RecursiveArrayIterator in combination with a RecursiveIteratorIterator:
$rii = new RecursiveIteratorIterator( new RecursiveArrayIterator( $myData ), RecursiveIteratorIterator::SELF_FIRST );
foreach( $rii as $key => $value )
{
echo $key;
// you can keep track of the current depth with:
$depth = $rii->getDepth();
}