I have an array like this. Array name is amount
Array
(
[0] => Array
(
[amount] => 0
)
[1] => Array
(
[amount] => 0
)
[2] => Array
(
[amount] => 0
)
[3] => Array
(
[amount] => 207.2
)
[4] => Array
(
[amount] => 1458.8
)
[5] => Array
(
[amount] => 207.2
)
)
Here I want to remove last key value from list when I display it into a table.
foreach(amount as key => values)
{
print_r($values);
echo"<br>";
}
When this print it should be show without last key element. like this
0
0
0
207.21
1458.8
I hope somebody will help me to solve this problem.
Hopefully
If you want to remove the last value if the array, you can:
First option, you can use array_pop to remove the last value.
//Assign the values on a temp array
$tempAmount = $amount;
//Remove the last value of the temp array.
array_pop( $tempAmount );
//You can loop as usual the temp array
http://php.net/manual/en/function.array-pop.php
Second option: You can use a condition, like:
foreach($amount as $key => $values)
{
if ( $key < count( $amount ) - 1 ) {
print_r($values);
echo"<br>";
}
}
You can use array_slice function to extract a sub-array from the index 0 and having size the size of old array - 1:
$newArray = array_slice($oldArray, 0, count($oldArray) -1);
Related
I do not know what is wrong with my php code. I want to have an Associative Array in the format. When I run my code I get this data. [KY] is an array in the [OH] array.
Array ( [Oh] => Array ( [state] => Oh ) [income] => 100 [count] => 1 [Ky] => Array ( [state] => Ky ) )
Array (
[OH] => Array
( [income] =>
[count] =>
)
[KY] => Array
( [income] =>
[count] =>
)
Here is my code
Example data in $array
Array ( [0] => Array (
[SurveyDate] => 1952-06-21
[Income] => 100
[CountyState] => Hamilton|Oh
[count] => 1 ) )
function update_array_value3( $array )
{
foreach ($array as $row)
{
$arrCountyState = explode( "|", $row['CountyState'] );
$key = $arrCountyState[1]; // OH or KY
if( !isset( $_SESSION['sIncome'][$key] ) )
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] = $row['Income'];
$_SESSION['sIncome'][$key]['count'] = 1;
} else
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] += $row['Income'];
$_SESSION['sIncome'][$key]['count'] += 1;
}
}
I can't tell you the root cause of the problem simply based on this snippet of code, but it seems $row either doesn't contain the data you expect it to, or doesn't contain any data.
In your code you reference $row['CountyState'], yet I don't see any array item called CountyState in $array.
Also, I'm not sure whether or not this is intentional, but in your foreach() loop it looks like $_SESSION['sIncome']['income'] and $_SESSION['sIncome']['count'] are being overwritten. Each time the loop encounters a new $key, it will overwrite those values.
I have following array
Array (
[0] => 1995,17500
[1] => 2052,17500
[2] => 2052,17500
[3] => 2236,30000
[4] => 2235,15000
[5] => 2235,40000
);
I have exploded the value with comma ,.
foreach($array as $key=>$value) {
$newar = explode(',', $value);
}
So I have similar first value i.e $newar["0"]. For example 2235 and 2052. And I would like to have sum of second value i.e $newar["1"].
How can I achieve following result with PHP.
Array (
[0] => 1995, 17500
[1] => 2052, 35000
[2] => 2036, 30000
[3] => 2235, 55000
)
You can create a new array key/index based and use array_key_exists to check if the key already exists. If so sum the value, if not create the key. This is not the exact result you want, but it's neater.
$newar = []; //New Array
foreach($array as $value) {
$explArr = explode(',', $value);
if(array_key_exists($explArr[0], $newar)){ //Check if the key already exists
$newar[$explArr[0]] += $explArr[1]; //Sum value to existing key
} else {
$newar[$explArr[0]] = $explArr[1]; //Create key
}
}
Your result array will look like this:
Array (
[1995] => 17500
[2052] => 35000
[2036] => 30000
[2235] => 55000
)
I have arrays within arrays, all with varying amounts of information. My CSV table currently has the fields Name, Email, and Phone Number.
Below is my array;
Array
(
[0] => Array
(
[0] => Name
[1] => Email
[2] => Phone Number
)
[1] => Array
(
[0] => Mick
[1] => mick#mick.com
[2] => 01234 324234
)
[2] => Array
(
[0] => james
[1] => james#james.com
[2] =>
)
[3] => Array
(
[0] => reg
[1] => reg#reg.com
[2] => 10293 467289
)
)
I wish to loop through and remove these null values and combine the Email and Phone Number into Info end up with an array which resembles
Array
(
[0] => Array
(
[0] => Name
[1] => Info
)
[1] => Array
(
[0] => Mick
[1] => mick#mick.com + 01234 324234
)
[2] => Array
(
[0] => james
[1] => james#james.com
)
[3] => Array
(
[0] => reg
[1] => reg#reg.com + 10293 467289
)
)
Here is my current script, I am recienving the error;
<b>Warning</b>: array_filter() expects parameter 2 to be a valid callback, no array or string given in <b>C:\Users\Lydia\Documents\XAMPP\htdocs\CSV.php</b> on line <b>21</b><br />
every time that I loop through the changeRow() function, any help greatly appreciated
index.php
<?php
include 'CSV.php';
header('Content-type: text/plain');
$file = read_csv('Book1.csv');
$input = changeRow($file);
CSV.php
....
....
function changeRow($rows){
$len = count($rows);
for($i = 0; $i < $len; $i++){
$rows = array_filter($rows[0],0);
}
}
Can use array_map() instead of foreach(). Example:
$file = read_csv('Book1.csv');
$input = array_map(function($v){
$phone = (isset($v[2]) && $v[2]) ? ' + '. $v[2] : '';
return array($v[0], $phone);
},$file );
if(isset($result[0][1])) $result[0][1] = 'Info';
print '<pre>';
print_r($input);
print '</pre>';
I'll provide two methods that output the requested array structure. (PHP Demo Link) These methods iterate the array, check if the iteration is dealing with the "column heading" subarray or not, then conditionally appending the value from subarray element [2] to subarray element [1] using + as glue.
Method #1: foreach()
foreach($array as $index=>$item){
if(!$index){
$result[]=['Name','Info'];
}else{
$result[]=[$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];
}
}
var_export($result);
Method #2 array_map()
var_export(
array_map(function($index,$item){
if(!$index){
return ['Name','Info'];
}else{
return [$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];
}
},array_keys($array),$array)
);
Output: (from either method)
array (
0 =>
array (
0 => 'Name',
1 => 'Info',
),
1 =>
array (
0 => 'Mick',
1 => 'mick#mick.com + 01234 324234',
),
2 =>
array (
0 => 'james',
1 => 'james#james.com',
),
3 =>
array (
0 => 'reg',
1 => 'reg#reg.com + 10293 467289',
),
)
ps. If you want to remove the $index==0 check that is iterated each time, you can manually overwrite the first subarray after the loop is finished like this: (PHP Demo Link) *this just means you will be "writing" data to the first subarray twice.
foreach($array as $item){
$result[]=[$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];
}
$result[0]=['Name','Info'];
var_export($result);
or
$result=array_map(function($item){return [$item[0],$item[1].(strlen($item[2])?" + $item[2]":'')];},$array);
$result[0]=['Name','Info'];
var_export($result);
pps. "Passing by Reference" can be used for this task, but I've elected not to use &$array because it can risk causing trouble "downscript" and many developers advise against using it until other methods are inadequate. Here is what that can look like: (PHP Demo Link)
foreach($array as &$item){
if(strlen($item[2])) $item[1].=" + $item[2]";
unset($item[2]);
}
$array[0]=['Name','Info'];
var_export($array);
unset($item); // var_export($item); // ($item = NULL)
The array is like this
Array 1
(
[2014-07-01] => Array
(
[date] => 2014-07-01
[totalr] => 13
)
[2014-07-02] => Array
(
[date] => 2014-07-02
[totalr] => 18
)
//... one for each day of the month
)
An then I have another array very similar to the one before the only key that changes is the key "total"
Array 2
(
[2014-07-01] => Array
(
[date] => 2014-07-01
[members] => 21
)
[2014-07-02] => Array
(
[date] => 2014-07-02
[members] => 30
)
//... one for each day of the month
)
So with both arrays I need to build a single array, so the final array need to be like this:
Final Array
(
[2014-07-01] => Array
(
[date] => 2014-07-01
[totalr] => 13
[members] => 21
)
[2014-07-02] => Array
(
[date] => 2014-07-02
[totalr] => 18
[members] => 30
)
// One for each day of the month
)
the key for each block is the same for each array... I already try array_merge didn't work... so how do I do that?...
UPDATE - 8-13-2014 08:12
Based on #ChicagoRedSox comment I find this function:
function juntaArrs($arr1, $arr2) {
if (!is_array($arr1) or !is_array($arr2)) { return $arr2; }
foreach ($arr2 AS $sKey2 => $sValue2) {
$arr1[$sKey2] = juntaArrs(#$arr1[$sKey2], $sValue2);
}
return $arr1;
}
$new_arr = juntaArrs($a1, $a2);
print_r($new_arr);
it works perfectly!! thank you.
// start with a new array
$newArr = array();
// for every key and value in array 1
foreach($arr1 as $k=>$v){
// add in the new array at key each key an array with date (the key),
// totalr (the second value in the sub-array) and numbers (the second value in
// the array 2 at the key position
$newArr[$k] = array('date'=>$k, 'totalr'=>$v[1], 'numbers'=>$arr2[$k][1]);
}
// it's what we obtain
print_r($newArr);
Refer to 2 array below:
$bar_arr =
Array
(
Array
(
[bar] => bar01.jpg
[position] => 1
)
Array
(
[bar] => bar02.jpg
[position] => 2
)
Array
(
[bar] => bar03.jpg
[position] => 3
)
)
$banner_arr =
Array
(
Array
(
[banner] =>
[position] => 1
)
Array
(
[banner] => banner02.jpg
[position] => 2
)
Array
(
[banner] => banner03.jpg
[position] => 3
)
)
$banner_arr[0][banner] don't have value, so I would like to remove this index. In the meantime$bar_arr[0][bar] would also be removed, I want to end up like this:
$bar_arr =
Array
(
Array
(
[bar] => bar02.jpg
[position] => 2
)
Array
(
[bar] => bar03.jpg
[position] => 3
)
)
$banner_arr =
Array
(
Array
(
[banner] => banner02.jpg
[position] => 2
)
Array
(
[banner] => banner03.jpg
[position] => 3
)
)
My question is how to compare this two array and remove both item in a specific index if either of the array have empty value.
Thanks
If you're just checking the value of banner and you assume that the two arrays are ordered identically, this is fairly simple (You might need to make a copy of banner_arr first ... not sure):
foreach ($banner_arr as $key => $banner) {
if (empty($banner['banner'])) {
unset($banner_arr[$key]);
unset($bar_arr[$key]);
}
}
More likely though, the order of the arrays can't be relied upon. In this case, just use an additional array of positions and track all the positions that need to be removed, and unset those:
$positions = array();
foreach ($banner_arr as $key => $banner) {
if (empty($banner['banner'])) {
$positions[] = $banner['position'];
unset($banner_arr[$key]);
}
}
then search through $bar_arr for corresponding positions:
foreach ($bar_arr as $key => $bar) {
if (in_array($bar['position'], $positions)) {
unset($bar_arr[$key]);
}
}
I'm assuming that both arrays are the same length and that the only possible missing values are in ['bar'] or ['banner'].
Basically I'd just loop through the array and store the valid values in new arrays;
$new_bar_arr = array();
$new_banner_arr = array();
$count = count($banner_arr);
$index = 0;
while($index < $count){
if(!empty($bar_arr[$index]['bar']) && !empty($banner_arr[$index]['banner'])){
$new_bar_arr[] = $bar_arr[$index];
$new_banner_arr[] = $banner_arr[$index];
}
$index++;
}
Assuming your count lines up like you've suggested:
$newArray = array_map( NULL, $banner_arr, $bar_arr );
foreach( $newArray as $key => $array ){
foreach( $array as $arr ){
if( $arr === NULL ){
unset( $newArray[$key] );
}
}
}
Even if it doesn't, I'd just make a new function and use array map still.