My Array shown as follows:
Array
(
[0] => Array
(
[amount_id] => 1
[enquiry_id] => 1
[project_id] => 1
)
[1] => Array
(
[amount_id] => 4
[enquiry_id] => 4
[project_id] => 4
)
[2] => Array
(
[amount_id] => 5
[enquiry_id] => 5
[project_id] => 5
)
)
This Array can be increase. How can i get value of each 'amount_id' from this array? What function should i use? Can for each function will work?
Just try with:
$input = array( /* your data */ );
$output = array();
foreach ($input as $data) {
$output[] = $data['amount_id'];
}
You can use a one-liner array_walk() to print those..
array_walk($arr,function($v){ echo $v['amount_id']."<br>";});
Working Demo
Do like this in array_map or Use array_column for The version PHP 5.5 or greater
$outputarr= array_map(function($item){ return $item['amount_id'];},$yourarr);
print_r($outputarr);
Try the following, this is accessing the specific array - easier to debug later on and better speed:
$num=count($your_array);
for($i="0"; $i<$num; $i++)
{
echo $your_array[$i]['amount_id'];
}
you could loop until $i < count($your_array) but it means that the count will run in every loop, for high performance sites I wouldn't do it.
you could access a specific element in a 2D array by $your_array[$the_index]['amount_id'] or other index.
Related
I want to merge some multidimension arrays and calculate the values of their items. For example :
Array
(
[0] => Array
(
[0] => Array
(
[nr_colete] => 6
)
)
[1] => Array
(
[0] => Array
(
[nr_colete] => 22
)
)
)
I want to get a solution to combine them and get a result such as
Array
(
[0] => Array
(
[nr_colete] => 6 + 22
)
)
Is there a native php function to help me get this result ? I try to found one.
I can't think of one single php native function to do this, but you can do it very simply using a foreach loop.
$sum = 0;
foreach($array AS $k => $value) {
$sum += $value[0]['nr_colete'];
}
Here is the code in action
No native function which will do that directly.But you can use array_column() and array_sum() two native function to get your desired result.
Check below code:-
$final_array[0]['nr_colete'] = array_sum(array_column(array_column($array,0),'nr_colete'));
print_r($final_array);
Output:- https://eval.in/873338
Reference:-
array_column()
array_sum()
I need some help formatting an array i get from an api, the current format is hard for me to work with so i want to change it for something more workable.
I have the following array:
[attributes] => Array
(
[0] => Array
(
[attribute] => Healing
[modifier] => 179
)
[1] => Array
(
[attribute] => Toughness
[modifier] => 128
)
[2] => Array
(
[attribute] => ConditionDamage
[modifier] => 128
)
and i want to turn it into this:
[attributes] => Array
(
[Healing] => 179
[Toughness] => 128
[ConditionDamage] => 128
)
any help would be appreciated.
If you're using PHP >= 5.5
$array['attributes'] = array_column(
$array['attributes'],
'attribute',
'modifier'
);
else
$array['attributes'] = array_walk(
$array['attributes'],
function (&$value) {
$value[$value['attribute']] = $value['modifier'];
unset($value['attribute'], $value['modifier']);
}
);
Using PHP >= 5.5, you can take advantage of array_column(), in conjunction with array_combine().
$new_arr = array_combine(array_column($arr, 'attribute'), array_column($arr, 'modifier'));
See demo
Otherwise, a simple foreach will work:
foreach ($arr as $ar) {
$new_arr[$ar['attribute']] = $ar['modifier'];
}
See demo
function flattenAPIarray($APIArray)
{
$flatArray = [];
foreach($APIArray as $element)
{
$key = array_keys($element);
$flatArray[$element[$key[0]]] = $element[$key[1]];
}
return $flatArray;
}
Try this function, I wrote for you. It's not generalized in any manner, but works fine with your multidimensional associative array. The clue is to use the array_keys() function, as you don't have any index to iterate using the foreach loop.
Hope that helps! (It's my first answer - be kind :o)
I have an array as so:
$diff_date_results =
Array (
[0] => Array ( [differential] => 7.7 [date] => 2012-12-30 )
[1] => Array ( [differential] => 8.2 [date] => 2012-12-31 )
[2] => Array ( [differential] => 9.9 [date] => 2013-01-03 )
)
I would like to extract all values from the differential key of each of the inner arrays to use the array_sum function on the newly created array.
I have this, which draws out the three numbers for me, but I get php errors for each number as an undefined index. (Notice: Undefined index: 7.7 in C:\wamp\www\jquery\test.php on line 55)
My code thus far is as follows:
$diff_results = array();
foreach($diff_date_results as $entry){
$diff_results[$entry['differential']];
}
print_r($diff_results);
I am sure it is simple, I have been screwing around with it for way too long now, any help would be wonderful!
Thanks.
$diff_results = array();
foreach($diff_date_results as $entry){
$diff_results[] = $entry['differential'];
}
//just for displaying all differential
print_r($diff_results);
Now, you can use array_sum on $diff_results.
Moreover, if you want to have sum then you can use below method too.
$diff_results = "";
foreach($diff_date_results as $entry){
$diff_results = $diff_results + $entry['differential'];
}
//$diff_results will have sum of all differential
echo $diff_results;
$diff_results = array_map($diff_date_results,
function($entry) { return $entry['differential']; });
Do it like this:
$diff_results = array();
foreach($diff_date_results as $key => $entry){
$diff_results[] .= $entry['differential']];
}
print_r($diff_results);
Thanks.
$diff_date_results = array (
0 => array ( 'differential'=> 7.7, 'date' => 20),
1 => Array ( 'differential' => 8.8, 'date' => 20 ),
2 => Array ( 'differential' => 9.8 ,'date' => 20 ),
);
$value_differential=array();
foreach( $diff_date_results as $key=>$value){
print_r($value);
$value_differential[]=$value['differential'];
}
print_r(array_sum($value_differential));
For anyone stumbling across this question as I have, the best solution in my opinion is a working version of Barmars as below:
$diff_results = array_map(function($entry)
{
return $entry['differential'];
},
$diff_date_results);
it's a more elegant, 1 line solution (which I've expand to 5 lines for readability).
Hi there I'm a bit confused on how I go about this. Any help would be greatly appreciated.
I have the following code.
$worms_level1 = $this->catch_the_worm_model->get_worms_by_level(1);
$captured_worms = array();
for ($i = 0; $i < $num_worms; $i++)
{
$captured_worms[$i] = array_rand($worms_level1);
}
return $captured_worms;
The $worms_level1 multidimensional array takes the following format:
Array ( [0] => Array ( [worm_id] => 1
[worm_name] => Verm
[worm_description] => The most common verm, not a huge threat but a great nuisance.
[worm_level] => 1
[worm_value] => 1 )
[1] => Array ( [worm_id] => 2
[worm_name] => Vermichav
[worm_description] => Vermichav loves a scuffle. He's been known to spit in Wormcatcher's eyes and inflict pain by cigarette burns.
[worm_level] => 1 [worm_value] => 1 )
)
At the minute the code is successful at selecting random arrays and saving them to a new array eg
Array ( [0] => 1 [1] => 1 )
but I also want the descendent arrays to be saved to the new array.
How about:
$captured_worms=array();
$howmany=20;
do{
$howmany-=count($captured_worms);//decreases $howmany by the number we already grabbed
shuffle($multiarray); //reorder the multiarray randomly
$captured_worms=array_slice($multiarray,0,$howmany);//get as many elements as you want
} while(count($captured_worms)<$howmany); //ensures at least $howmany
I've got an array like this
Array
(
[0] => Array
(
[0] => Array
(
[szam] => 8
[index] => 0
)
)
[1] => Array
(
[0] => Array
(
[szam] => 1
[index] => 0
)
[1] => Array
(
[szam] => 7
[index] => 1
)
)
I thought that my last cmp will work fine
function maxSzerintCsokkeno($item1,$item2)
{
if ($item1['szam'] == $item2['szam']) return 0;
return ($item1['szam'] < $item2['szam']) ? 1 : -1;
}
with foreach
foreach ($tomb as $kulcs => $adat) usort($adat,"maxSzerintCsokkeno");
but it dosen't do anything, advise?
foreach ($tomb as $kulcs => $adat) usort($adat,"maxSzerintCsokkeno");
This only sorts the subarray array $adat. And this only exists temporarily until foreach loops over the next one. The lazy option here would be to use a reference:
foreach ($tomb as & $adat) usort($adat,"maxSzerintCsokkeno");
Notice the &. This way the modification on $adat will be applied directly in the parent array.
You're sorting a temporary variable, meaning the changes are not applied. The following should work for you:
for($i = 0, $length = count($tomb); $i < $length; $i++)
{
usort($tomb[$i], "maxSzerintCsokkeno");
}
When iterating through the foreach loop, the key and value variables ($kulcs and $adat in your code) are copies of the actual values in the array. Like Tim Cooper said, you are actually sorting a copy of the original value.
You can also pass the value by reference in your foreach loop. This means that you will be modifying the original value:
foreach ($tomb as $kulcs => &$adat) usort($adat,"maxSzerintCsokkeno");