Combining different array cells to one array on match - php

I can not wrap my head around how to do the following. I have two different lenght and different dimensional arrays that I want to combine so that the result array will have arrays1 + array2 cell that did not match.
This should help you understand what I mean
$dbquery_results1[0][] = array("1","5","b99");
$dbquery_results1[1][] = array("4","12","www");
$dbquery_results1[2][] = array("10","32","ccc");
$dbquery_results1[3][] = array("7","142","xx");
$dbquery_results2[0][] = array("c","10");
$dbquery_results2[1][] = array("as","1");
$dbquery_results2[2][] = array("fe","7");
$dbquery_combination[0][] = array("1","5","b99","as");
$dbquery_combination[1][] = array("7","142","xx","fe");
What I would like to get done
$i=0;
while(!empty($dbquery_results1[$i][0])) {
If($dbquery_results1[$i][0] == $dbquery_results2[any of the dimensions here][2])
{
$dbquery_combination[] = $dbquery_results1[$i][]+ $dbquery_results2[x-dimension][2];
} $i++;
}
So only if array1 has at [][0] same value as array2 [any dimension][1] will array1 + the array2 cell that is different be saved at array3.
Sorry that I am not too good expressing myself. Thanks a lot in advance.

So if you don't have the choice you can do it like this :
<?php
$dbquery_results1[0] = array("1","5","b99");
$dbquery_results1[1] = array("4","12","www");
$dbquery_results1[2] = array("10","32","ccc");
$dbquery_results1[3] = array("7","142","xx");
$dbquery_results2[0] = array("c","10");
$dbquery_results2[1] = array("as","1");
$dbquery_results2[2] = array("fe","7");
foreach($dbquery_results1 as $line_r1)
{
foreach($dbquery_results2 as $line_r2)
{
if($line_r1[0] == $line_r2[1])
{
$line = $line_r1;
$line[] = $line_r2[0];
$dbquery_combination[] = $line;
}
}
}
print_r($dbquery_combination);
?>
And the result is :
Array (
[0] => Array ( [0] => 1 [1] => 5 [2] => b99 [3] => as )
[1] => Array ( [0] => 10 [1] => 32 [2] => ccc [3] => c )
[2] => Array ( [0] => 7 [1] => 142 [2] => xx [3] => fe )
)

I think you are complicating the problem. I suppose that your array are the result of SQL request ? If it's the case, you should prefer to use joint SQL request.
//Coment Answer : Are they on the same server ? If yes, you can make request on multiple database at the same time by specifying full qualification.

Related

PHP compare duplicates from array with multiple string data

I have an array with four columns (divided by ";") per index number. The data is coming from a csv file.
Example Data:
John = Firstname
Doe = Lastname
Playground = Description
john.doe#example.com = Email
print_r($dataArray);
Array
(
[0] => John;Doe;Playground;john.doe#example.com
[1] => John;Doe;Playground test;john.doe#example.com
[2] => John;Doe;test Playground;john.doe#example.com
[3] => Johnny;Dawson;Test Area;john.doe#example.com
)
Now I want to remove the duplicates with array_unique.
But I only want to compare the "firstname" and the "lastname".
If the firstname and the lastname has multiple results then remove the duplicate entry.
In this case [1] and [2]
$finalArray = array_unique($dataArray);
array unique will only work if all rows have the same data e.g.
[0] => John;Doe;Playground;john.doe#example.com
[1] => John;Doe;Playground;john.doe#example.com
Goal: Final result
Array
(
[0] => John;Doe;Playground;john.doe#example.com
[1] => Johnny;Dawson;Test Area;john.doe#example.com
)
What is a good way to handle this case?
$a will be unique. notice the array keys that remained the same.
foreach($a as $k=>$v)
{
list($name,$family) = explode(';', $v);
if( isset($temp[$name.$family]) )
unset($a[$k]);
else
$temp[$name.$fam] = true;
}

How can I restructure this array to condense the data into a more usable format in 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

PHP: Why missing values in associative array?

Can someone please put me out of my misery and explain why I'm missing the middle value when I try to push the results of a preg_match into another array? It's either something silly or a vast gap in my understanding. Either way I need help. Here is my code:
<?php
$text = 'The group, which gathered at the Somerfield depot in Bridgwater, Somerset,
on Thursday night, complain that consumers believe foreign meat which has been
processed in the UK is British because of inadequate labelling.';
$word = 'the';
preg_match_all("/\b" . $word . "\b/i", $text, $matches, PREG_OFFSET_CAPTURE);
$word_pos = array();
for($i = 0; $i < sizeof($matches[0]); $i++){
$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];
}
echo "<pre>";
print_r($matches);
echo "</pre>";
echo "<pre>";
print_r($word_pos);
echo "</pre>";
?>
I get this output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => The
[1] => 0
)
[1] => Array
(
[0] => the
[1] => 29
)
[2] => Array
(
[0] => the
[1] => 177
)
)
)
Array
(
[The] => 0
[the] => 177
)
So the question is: why am I missing the [the] => 29? Is there a better way? Thanks.
PHP arrays are 1:1 mappings, i.e. one key points to exactly one value. So you are overwriting the middle value since it also has the key the.
The easiest solution would be using the offset as the key and the matched string as the value. However, depending on what you want to do with the results a completely different structure might be more appropriate.
First you assign $word_pos["the"] = 29 and then you OVERWRITE IT with $word_pos["the"] = 177.
You don't overwrite The because indexes are case sensitive.
So maybe use an array of objects like this:
$object = new stdClass;
$object->word = "the"; // for example
$object->pos = 29; // example :)
and assign it to an array
$positions = array(); // just init once
$positions[] = $object;
alternatively you can assign an associative array instead of the object, so it would be like
$object = array(
'word' => 'the',
'pos' => 29
);
OR assign the way you do, but instead of overwriting, just add it to an array, like:
$word_pos[$matches[0][$i][0]][] = $matches[0][$i][1];
instead of
$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];
so you get something like:
Array
(
[The] => Array
(
[0] => 0
)
[the] => Array
(
[0] => 29
[1] => 177
)
)
Hope that helps :)
What is happening actually :
when i=0,
$word_pos[The] = 0 //mathches[0][0][0]=The
when i=1
$word_pos[the] = 29
when i=3
$word_pos[the] = 177 //here this "the" key overrides the previous one
//so your middle 'the' is going to lost :(
Now an array based solution can be like this :
for($i = 0; $i < sizeof($matches[0]); $i++){
if (array_key_exists ( $matches[0][$i][0] , $word_pos ) ) {
$word_pos[$matches[0][$i][0]] [] = $matches[0][$i][1];
}
else $word_pos[$matches[0][$i][0]] = array ( $matches[0][$i][1] );
}
Now if you dump $word_pos the output should be :
Array
(
[The] => Array
(
[0] => 0
)
[the] => Array
(
[0] => 29 ,
[1] => 177
)
)
Hope that helps.
Reference : array_key_exist

If value exists in one PHP array, add value to second array

I have two PHP arrays. One contains a group name and another contains a pay wage value.
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 1 [3] => 3 );
This means there are four employees on the schedule. Two are assigned to group 1, another to group 4 and the last to group 3.
The second array is as follows:
$tot_wages_array = Array ( [0] => 500 [1] => 44 [2] => 80 [3] => 11.25 );
This is a sample array of each employee's wage. Both arrays are constructed in order as values are added in a mysql while loop as it pulls the info from the database.
Later on down the line, I combine the two arrays to get one array where the key is the group number and the value is the total wages for that group:
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
This works like a charm EXCEPT for when more than one employee is assigned to the same group. These arrays are built in a mysql while loop as it loops through each employee's info:
array_push($tot_wages_array, $totemp_wages_sch); // Add their wage to the array
array_push($group_wages_array, $emp_data['group_id']); // Add their group to the array
Instead of just pushing the data to the array, I need to do this... I know the english but I don't know how to code it:
If $emp_data['group_id'] exists as value in $group_wages_array, add nothing to this array but get the key. Add $totemp_wages_sch to $tot_wages_array where key = group_wages_array key
I know it sounds more like an SQL query but I have to keep the keys and values in order so that they can be combined later in the page. If I can get this to work right, The arrays shown in the example would be:
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 3 );
$tot_wages_array = Array ( [0] => 580 [1] => 44 [2] => 11.25 );
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
$combined_group_wages = Array ( [1] => 580 [4] => 44 [3] => 11.25 );
...I've got to make this work using PHP. Any ideas?
I came up with a solution based on a combination of two of the answers submitted below. Here it is if it can help someone:
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] += $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
array_push($tot_wages_array, $totemp_wages_sch);
}
This should do it:
$group_wages_array = array(1, 4, 1, 3);
$tot_wages_array = array(500, 44, 80, 11.25);
$combined_group_wages = array();
for ($i=0; $i<count($group_wages_array); $i++) {
$group = $group_wages_array[$i];
if (array_key_exists($group_wages_array[$group], $combined_group_wages)) {
$combined_group_wages[$group] += $tot_wages_array[$i];
} else {
$combined_group_wages[$group] = $tot_wages_array[$i];
}
}
print_r($combined_group_wages);
Yields:
Array
(
[1] => 580
[4] => 44
[3] => 11.25
)
But I recommend that you just switch to using objects to better represent your data.
If I could see the entirety of the code that would help a lot, but here's your English converted to php. Show me more code and I can perfect it, until then try this ->
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] = $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
}

Using array_rand to select a top level array and all it's decendents

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

Categories