Merge x arrays with array_merge() - php

since I've tried different things - like for/while-loops, I finally ended up here. What I'm trying to do is to merge different x arrays (from a form) into one array, so that I can count the answers. My code for merging actually looks like this:
foreach($_POST as $key =>$value){
foreach ($value as $answer){
echo $answer."<br />";
}
$tmp+=1;
$data[$key] = $value;
}
$results = array_merge($data['q1'], $data['q2']);
I'd like to input the content of array_merge based on how many questions (q1, q2, ...) are in the form. So I tried this:
$array_loop = array();
for ($k = 1 ; $k < $tmp; $k++) {
$array_loop.='$data["q' . $k . '"], ';
};
Of course, it's not working because it's an array so string conversion. Any hints?

you can use
$result = array_merge(...$array_loop);
to save multiple arrays into one array

Related

Combine 2 Arrays In Foreach in PHP

I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.
This is my username list from database.
$digits = [1,2,3,4];
$results = $db->table($usernames)
->where('memberID', $mID)->limit(10)
->getAll();
foreach ($results as $result) {
echo $result->userName;
}
I tried this:
$combined = array_merge($digits, $results);
foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
{
echo $single.'<br>';
echo $results->userName;
},
}
You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:
$combined = array_combine($digits, $results);
foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}
foreach operates on only one array at a time.
The way your array is structured, you can use array_combine() function to combine them into an array of key-value pairs then foreach that single array

PHP create 1 array of 4 arrays ordered by index

I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}

can you foreach two arrays at once?

foreach (($_POST['pedimento'] as $value) && ($_POST['observacion'] as $obs))
{
$sql1=mysql_query("INSERT INTO pedimento (`error`,`observacion`) VALUES ('$value','$obs')");
}
im trying to insert data from two arrays, does anyone know how can i get the data from the two arrays simultaneously, and save them together in one sql statement?
I would turn your foreach into a for loop with an int counter:
for($i = 0; $i < array.length; $i++)
{
$x = arrayOne[$i];
$y = arrayTwo[$i];
$sql1=mysql_query("INSERT INTO pedimento (error,observacion) VALUES ('$x','$y')"); }
}
PHP isn't my strong suit (not by a long shot) but I checked that For loops work. As long as array logic works even remotely like other languages, the above statement should loop through both arrays (assuming they are the same length) and create an INSERT statement with the two values it finds.
Do not use $_POST values in a query like this! Move to prepared statements using PDO or MySQLi.
The only way this makes sense as the other answers assume, is if the arrays are the same length and have identical keys so:
foreach ($_POST['pedimento'] as $key => $value)
{
$obs = $_POST['observacion'][$key];
$sql1 = mysql_query("INSERT INTO pedimento (`error`,`observacion`)
VALUES ('$value','$obs')");
}
foreach (array_combine($_POST['pedimento'], $_POST['observacion']) as $value => $val) {
echo $value;
echo $val;
}
what about this?
$array1 = array("A","B","C");
$array2 = array(1,2,3);
foreach (array_combine($array1,$array2) as $first => $second) {
echo $first." ". $second;
}
output:
A 1B 2C 3

Creating a ranked list from multiple arrays

I have 3 arrays that return a url,title,snippet and score from 3 different search engines, the score starts at 100 for the element in the array, the second 99 and so on, I'm trying to combine all 3 into one array. If the urls match from the different arrays I want to add the scores together and then delete the duplicate url. If there is no match between the urls then I just want to put this element into the combined array.
The final combined list should contain all distinct urls with its score,title and snippet, here are my array structures
googleArray
$x=0;
$score=100;
foreach ($js->items as $item)
{
$googleArray[$x]['link'] = ($item->{'link'});
$googleArray[$x]['title'] = ($item->{'title'});
$googleArray[$x]['snippet'] = ($item->{'snippet'});
$googleArray[$x]['score'] = $score--;
$x++;
}
blekkoArray
$score = 100;
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = ($item->{'url'});
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'] = $score--; // assign the $score value here
$i++;
}
bingArray
foreach($jsonObj->d->results as $value)
{ $i = 0;
$bingArray[]['Url'] = ($value->{'Url'});
$bingArray[]['Title'] = ($value->{'Title'});
$bingArray[]['Description'] = ($value->{'Description'});
$bingArray[]['score'] = $score--;
$i++;
}
Any help would be great, thanks in advance
This solution depends on a couple of things to work. First, the url and score keys need to be the same, i.e. all lower case and none that are "link." Secondly, the URLs have to be normalized, because they serve as the key for the array. If there are any differences in the URLs, they will show up more than once in the final array.
$merged = array_merge($googleArray, $blekkoArray);
$merged = array_merge($merged, $bingArray);
$combined = array();
foreach ($merged as $key => $value){
$score = (isset($combined[$value['url']]['score'])) ? $value['score'] + $combined[$value['url']]['score'] : $value['score'];
$combined[$value['url']] = $value;
$combined[$value['url']]['score'] = $score;
}
If you don't want to keep the URLs as the key, add this line:
$combined = array_values($combined);
If you want to sort the array by score, you can use usort:
usort($combined, function ($a, $b){
return $b['score'] - $a['score'];
});
print_r($combined);

How can I iterate through two arrays at the same time without re-iterating through the parent loop? [duplicate]

This question already has answers here:
php looping through multiple arrays [duplicate]
(8 answers)
Closed 9 years ago.
How can I iterate through two arrays at the same time that have equal sizes ?
for example , first array $a = array( 1,2,3,4,5);
second array $b = array(1,2,3,4,5);
The result that I would like through iterating through both is having the looping process going through the same values to produce a result like
1-1
2-2
3-3
4-4
5-5
I tried to do it this way below but it didn't work , it keeps going through the first loop again
foreach($a as $content) {
foreach($b as $contentb){
echo $a."-".$b."<br />";
}
}
Not the most efficient, but a demonstration of SPL's multipleIterator
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));
$newArray = array();
foreach ( $mi as $value ) {
list($value1, $value2) = $value;
echo $value1 , '-' , $value2 , PHP_EOL;
}
Use a normal for loop instead of a foreach, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
If they're the same size, just do this:
foreach($a as $key => $content){
$contentb = $b[$key];
echo($content."-".$contentb."<br />");
}

Categories