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).
Related
I have an array like this:
$arr = array ( [0] => array("red","green"),
[1] => array("blue","yellow")
);
And this is expected result:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
See? I want to merge all items of $arr (which are also array themselves). How can I do that?
I can do a loop on it and then use array_merge() every time like this:
$res = [];
foreach ( $arr as $item ) {
$res = array_merge($res, $item);
}
It works as well. But I guess I can write it better. Any idea?
You can do trick with call_user_func_array:
$result = call_user_func_array('array_merge', $arr);
This trick is possible, because array_merge accept dynamic arguments count.
It's a style exercise, but if the structure remains the same as in your example, you can play with this:
$arr = array ( '0' => array("red","green"),
'1' => array("blue","yellow")
);
$res = explode(",",str_replace(array('[',']'),'',json_encode($arr)));
Hope this helps.
You declare array in wrong way:
$arr = array ( 0 => array("red","green"),
1 => array("blue","yellow")
);
The error reported by PHP says it clearly:
Fatal error: Illegal offset type in /in/Hhfqa on line 3
Line 3 in your example is exactly line of first array element.
Please check http://php.net/manual/en/language.types.array.php
I will try to explain the data I'm working with first, then I'll explain what I hope to do with the data, then I'll explain what I've tried so far. Hopefully someone can point me in the right direction.
What I'm working with:
I have an array containing survey responses. The first two items are the two answers for the first question and responses contains the number of people who selected those answers. The last three items are the three answers for the other question we asked.
Array
(
[0] => Array
(
[survey_id] => 123456789
[question_text] => Have you made any changes in how you use our product this year?
[d_answer_text] => No
[responses] => 92
)
[1] => Array
(
[survey_id] => 123456789
[question_text] => Have you made any changes in how you use our product this year?
[answer_text] => Yes
[responses] => 30
)
[2] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => Less Positive
[responses] => 14
)
[3] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => More Positive
[responses] => 35
)
[4] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => No Change
[responses] => 72
)
)
What I want to achieve:
I want to create an array where the question_text is used as the key (or I might grab the question_id and use it instead), use the answer_text as a key, with the responses as the value. It would look something like this:
Array
(
[Have you made any changes in how you use our product this year?] => Array
(
[No] => 92
[Yes] => 30
)
[How would you describe your interaction with our staff compared to prior years?] => Array
(
[Less Positive] => 14
[More Positive] => 35
[No Change] => 72
)
)
Here's what I've tried:
$response_array = array();
foreach($result_array as $value){
//$responses_array['Our question'] = array('answer 1'=>responses,'answer 2'=>responses);
$responses_array[$value['question_text']] = array($value['answer_text']=>$value['responses']);
}
This does not work because each loop will overwrite the value for $responses_array[$question]. This makes sense to me and I understand why it won't work.
My next thought was to try using array_merge().
$responses_array = array();
foreach($result as $value){
$question_text = $value['question_text'];
$answer_text = $value['answer_text'];
$responses = $value['responses'];
$responses_array[$question_text] = array_merge(array($responses_array[$question_text],$answer_text=>$responses));
}
I guess my logic was wrong because it looks like the array is nesting too much.
Array
(
[Have you made any changes in how you use our product this year?] => Array
(
[0] => Array
(
[0] =>
[No] => 92
)
[Yes] => 30
)
My problem with array_merge is that I don't have access to all answers for the question in each iteration of the foreach loop.
I want to design this in a way that allows it to scale up if we introduce more questions with different numbers of answers. How can this be solved?
Sounds like a reduce job
$response_array = array_reduce($result_array, function($carry, $item) {
$carry[$item['question_text']][$item['answer_text']] = $item['responses'];
return $carry;
}, []);
Demo ~ https://eval.in/687264
Update
Remove condition (see #Phil comment)
I think you are looking for something like that :
$output = [];
for($i = 0; $i < count($array); $i++) {
$output[$array[$i]['question_text']] [$array[$i]['answer_text']]= $array[$i]['responses'];
}
print_r($output);
Slightly different approach than the answer posted, more in tune with what you'v already tried. Try This:
$responses_array = array();
$sub_array = array();
$index = $result[0]['question_text'];
foreach($result as $value){
$question_text = $value['question_text'];
$answer_text = $value['answer_text'];
$responses = $value['responses'];
if (strcmp($index, $question_text) == 0) {
$sub_array[$answer_text] = $responses;
} else {
$index = $question_text;
$responses_array[$index] = $sub_array;
$sub_array = array();
}
}
Edit: Found my mistake, updated my answer slightly, hopefully this will work.
Edit 2: Working with example here: https://eval.in/687275
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)
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.
Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}