Combine 2 Arrays In Foreach in PHP - 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

Related

PHP foreach multiple arrays

Hi there I have been at a loss with the foreach loop. What I'm trying to do is have multiple arrays in a foreach loop.
All I can find on the Internet is how to get a single value out of the arrays. I managed to get two working with:
foreach (array_combine($slides, $headers) as $slide => $header)
But that's limited to only two arrays. I just want list after list for more than two arrays.
Since array_combine is working for you with two arrays, that means you want the elements at the same position, so you can use the same key:
foreach ($slides as $key => $slide) {
echo $slide;
echo $headers[$key];
echo $another[$key];
//etc...
}
If the keys may not match then re-index before the loop:
$slides = array_values($slides);
$headers = array_values($headers);
$another = array_values($another);
You will run into issues if the arrays aren't the same length so you might check:
if(isset($headers[$key])) { echo $headers[$key]; }
Another way might be to map them into a multi-dimensional array grouped one from each in a sub-array. The integer index for $values matches the order of the arrays in array_map:
foreach(array_map(null, $slides, $headers, $another) as $values) {
echo $values[0];
echo $values[1];
echo $values[2];
}
Or assign the array values to variables:
foreach(array_map(null, $slides, $headers, $another) as $values) {
list($s, $h, $a) = $values;
echo $s;
echo $h;
echo $a;
}

How to print PHP array values without square brackets and symbols?

I want to print an array without printing the square brackets and the word "Array", for example if I do
print_r($Array);
I will get this:
Array ( [0] => Example0 [1] => Example1)
How can I get this?
Example0
Example1
Any of these ways should work just fine.
// First way
print_r(implode("<br>", $your_array));
// Second way
for ($i = 0; $i < count($your_array); $i++) {
print_r($your_array[$i]);
echo "<br>";
}
// Third way
foreach ($your_array as $value) {
print_r($value);
echo "<br>";
}
The first method works for one-dimensional arrays only. If you have multidimensional arrays, you need to use for loops and to check whether the current element is an array or not and recursively enter into more for loops in order to print out all the data.
You can do it in this way:
function print_array ($array) {
foreach ($array as $key => $value) {
if (is_array ($value)) {
print_array ($value);
} else {
echo ($value."<br />");
}
}
}
You could use array walk recursive
$array = ['Example0','Example1', ['Example2']];
array_walk_recursive($array,function($item,$key){echo"$item\n";});
// tip use <br> instead of \n for HTML
Outputs
Example0
Example1
Example2
See it online
array_walk_recursive — Apply a user function recursively to every member of an array
So this will seamlessly handle multi-dimensional arrays, as my example shows.
If I understood correctly, you want to print the values for each key. You can use
foreach ($Array as $value) {
print_r($value);
echo "\n";
}
This will result in
Example0
Example1
foreach($Array as $key) {
echo $key.", ";
}

Merge array with common value

I have two arrays namely arr and arr2.
var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];
var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];
Is it possible to get array below shown from above two arrays?
result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];
If i use array_merge then i get answer as
result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];
You must decode JSON to arrays, manually merge them and again encode it to JSON :)
<?php
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$result = [];
foreach ($arr as &$item) {
if (empty($arr2))
break;
foreach ($arr2 as $key => $item2) {
if ($item['month'] === $item2['month']) {
$item = array_merge($item, $item2);
unset($arr2[$key]);
continue;
}
}
}
if (!empty($arr2))
$arr = array_merge($arr, $arr2);
echo json_encode($arr);
The first function that comes to mind is array_merge_recursive(), but even if you assign temporary associative keys to the subarrays, you end up with multiple January values in a new deep subarray.
But do not despair, there is another recursive function that can do this job. array_replace_recursive() will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.
Here is a one-liner that doesn't use foreach() loops or if statements:
Code: (Demo)
$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));
Output:
[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]
The breakdown:
echo json_encode( // convert back to json
array_values( // remove the temp keys (reindex)
array_replace_recursive( // effectively merge/replace elements associatively
array_column($arr,NULL,'month'), // use month as temp keys for each subarray
array_column($arr2,NULL,'month') // use month as temp keys for each subarray
)
)
);
You should write your own function to do that
$res = [];
foreach ($arr as $item) {
$res[$item['month']] = $item;
}
foreach ($arr2 as $item) {
$res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item;
}
var_dump($res);

Iterating a multi-dimensional array and mixing it

im trying to mix my multi dimension arrays, and it iterates fine, but the output isnt what im trying to accomplish, i need to mix the values.
array= [ [ p ,t ,j ] , [ 9 , 3 , 6 ] ];
foreach($array as $value) {
foreach($value as $key => $val) {
echo $val;
}
}
}
array output: p,9,t,3,j,6 //should be
Mine is: p,t,j,9,3,6
Simplest approach
foreach($array[0] as $key => $value) {
echo $value, $array[1][$key];
}
if i understand you this is your answer:
//creat an empty array to save the new result
$result= array();
//do this for incrementing
$i=0;
//your arrays here and looping it
$array=array(array( p ,t ,j ) , array( 9 , 3 , 6 ) );
foreach($array as $a){
if(is_array($a)){
foreach($a as $b){
$result[$i]= $b;
}//end foreach
}else{
$result[$i]= $a;
}//end else
$i++;
}//end foreach
//then print_r to show your array
print_r($result);
have a nice day ^_^
by 'mix' do you mean trying to combine the secondary arrays into one long array? If that is the case:
$finalArray = array();
foreach($array as $value) {
$finalArray = array_merge($finalArray, $value);
}
edit: now that I look at it, I didn't quite echo the output like you needed, but the output should be in the correct order in the $finalArray and this should work with any amount of inner arrays.

How to get the keys in a PHP Array by position?

I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()

Categories