new to the stackoverflow community, so do be forgiving if I've done anything incorrect. As I'm an amateur in coding in php, I'm currently facing a difficulty in multi dimensional arrays.
Currently, I have this array being returned to me.
Array(
[trialID] => 1
[trialMixedArray] => 1,2,3,4,5,6
[trialStatus] => active
[trialAddedDate] => 2017-11-13 09:56:03
)
How do I split the trialMixedArray and return it to the original array so that it becomes formatted to be like the following result:
Array(
[trialID] => 1
[trialMixedArray] => Array(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[trialStatus] => active
[trialAddedDate] => 2017-11-13 09:56:03
)
Thanks for the help in advance! Cheers! :)
Use explode function, which splits string to array. Manual.
$results['trialMixedArray'] = explode(',', $results['trialMixedArray']);
you can try something like this
$finalArray = [];
fetchItems($array_variable) {
foreach($array_variable as $item){
if(is_array($item) {
fetchItems($item);
} else {
$finalArray[] = $item;
}
}
}
fetchItems($originaArray);
Use explode function to split any string based on a key.
The syntax is explode('key',string);
Related
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
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.
Ok so I have been struggling with this for hours now and I cannot seem to figure out what I'm trying to do. I have an array with many percent values placed inside and I'm printing out the first 5 of them. The $percent variables are acquired through similar_text
$array=array($percent12, $percent13, $percent14,
$percent15, $percent16, $percent17,
$percent18, $percent19, $percent110,
$percent111, $percent112, $percent113,
$percent114, $percent115, $percent116,
$percent117, $percent118, $percent119,
$percent120);
print_r(array_slice($array,0,5));
and it outputs like this:
Array ( [0] => 36.015505697169 [1] => 2.4181626187962 [2] => 2.4181626187962 [3] => 5.2153134902083 [4] => 100 )
So what i'm trying to figure out here is if it's possible to print the results of my array as they are listed above. example output would look like this:
Array ( [percent12] => 36.015505697169 [percent13] => 2.4181626187962 [percent14] => 2.4181626187962 [percent15] => 5.2153134902083 [percent16] => 100 )
i feel like this isn't possible, but if not, is there a way to assign the
[0]=> 36.015505697169 [1]=> 2.4181626187962
...etc to output something else say like:
[web0]=> 36.015505697169 [web1] => 2.4181626187962
Please help!! It's driving me crazy!!
You need to make it an associative array:
$array=array('percent12' => $percent12,
'percent13' => $percent13,
...);
I recommend using array_combine()
Basically you're just going to setup your new array with the keys, and pass in your current array for the values, thus creating a new array with the keys you want in the right place.
Try like
$myArr = array_slice($array,0,5);
$i = 0;
foreach($myArr as $key => $value) {
$newArr['web'.$i++] = $value;
}
print_r($newArr);
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).
I have a large array of scraped names and prices similar to the following:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [4] => lemon [5] => grape [6] => pear5 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
I would like to remove the fruit names that are not immediately followed by a price. In the above example this would remove: [4] => lemon [5] => grape [6] => pear5 resulting in the following output:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
If the array needs to be converted to a string in order for me to do this that is not a problem, nor is adding values between the array items in order to aid with regex searches. I have so far been unable to find the correct regular expression to do this using preg_match and preg_replace.
The most important factor is the need to maintain the sequential order of the fruits and prices in order for me at a later stage to convert this into an associative array of fruits and prices.
Thanks in advance.
Why involve regular expressions? This is doable with a simple foreach loop wherein you iterate over the array and remove names that follow names:
$lastWasPrice = true; // was the last item a price?
foreach ($array as $k => $v) {
if (ctype_alpha($v)) {
// it's a name
if (!$lastWasPrice) {
unset($array[$k]); // name follows name; remove the second
}
$lastWasPrice = false;
}
else {
// it's a price
$lastWasPrice = true;
}
}
The following code does both of your tasks at once: getting rid of the fruit without value and turning the result into an associative array of fruits with prices.
$arr = array('apple', '£0.40', 'banana', '£1.80', 'lemon', 'grape', 'pear', 'melon', '£2.32', 'kiwi', '£0.50' );
preg_match_all( '/#?([^£][^#]+)#(£\d+\.\d{2})#?/', implode( '#', $arr ), $pairs );
$final = array_combine( $pairs[1], $pairs[2] );
print_r( $final );
First, the array is converted to a string, separated by '#'. The regex captures all groups of fruits with prices - each stored as a separate subgroup in the result. Combining them into an associative array is a single function call.
Something like this might help you
$array = ...;
$index = 0;
while (isset($array[$index + 1])) {
if (!is_fruit($array[$index + 1])) {
// Not followed by a fruit, continue to next pair
$index += 2;
} else {
unset($array[$index]); // Will maintain indices in array
$index += 1;
}
}
Not tested though. Also, you need to create the function is_fruit yourself ;)
Without reformatting it, I don't think you can do it with preg_match or preg_replace-- maybe, but nothing is coming to mind.
What is creating that array? If possible, I would alter it to look more like:
Array([apple] => £0.40 [banana] => £1.80 [lemon] => [grape] => '' [pear ] => '' [melon => £2.32 [kiwi] => £0.50)
Then array_filter($array) is all you'd need to clean it up. If you can't alter the way the original array is created I'd lean towards creating key/value array out of the original.
Try replacing the pattern ** => ([a-zA-Z])** with ** => £0.00 $1**
Basically searching for the context where there is null price and inserting zero pounds.
Hope this helps.
Good luck
Simply do this :
<?php
for($i=0;$i<count($my_array);$i++)
{
if($my_array[$i+1]value=="")
unset($my_array[$i])
}
?>
assume $a is your array.
function isPrice($str) {
return (substr($str, 0, 1) == '£');
}
$newA = array();
for($i=0;$i<count($a);$i++) {
if( isPrice($a[$i]) != isPrice($a[$i+1]) ){
$newA[] = $a[$i];
}
}