Iterating a multi-dimensional array and mixing it - php

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.

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

How to compare LARGE Multidimensional arrays in PHP

I searched and searched over this foro and this question is not in it, please help me with this if someone can.
I have two LARGE multidimensional arrays with the following formats
$arr1 = array( array (n1,n2,..,n=5), array (n1,n2,..,n=5), n-arrays (n1,...,n5) )
Note: the subarrays of arr1 have 5 numbers each .
$arr2 = array( array (n1,n2,..,n=4), array (n1,n2,..,n=4), n-arrays (n1,...,n4) )
Note: the subarrays of arr2 have 4 numbers each .
Now, I need to remove from arr1 the sub-arrays that include the sub-arrays in arr2. Please, see below an example:
With this two arrays:
$arr1 = array(array(1,2,6,8,10), array(2,4,6,8,10), array(20,40,60,80,100));
$arr2 = array(array(1,6,8,10), array(200,400,600,800));
The code must return:
$ret = array(array(2,4,6,8,10), array(20,40,60,80,100));
Because the numbers of (1,6,8,10) are in (1,2,6,8,10)
This is that code that I'm using now, and it works, but for a limmited number of data.... I think I need something more efficient
foreach ($arr1 as $key => $a ) {
foreach ($arr2 as $a2) {
if ( count(array_diff($a, $a2)) == 1 ) {
unset($arr1[$key]); break; }
}
}
}
You can use empty() to check if all elements were removed during array_diff()
foreach ($arr1 as $key => $v1) {
foreach ($arr2 as $v2) {
if (empty(array_diff($v2, $v1))) {
unset($arr1[$key]);
break;
}
}
}
print($arr1);
Or if your sticking with count(), you can change it to something like
if ( count(array_diff($a2, $a) < 1)) { // array_diff has the $a2 first
unset($arr1[$key]); break;
}

How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas?

How can I get the list of values from my array:
[data] => Array
(
[5] => Array
(
[0] => 19
[1] => 18
[2] => 20
)
[6] => Array
(
[0] => 28
)
)
Expected output result string will be: 19,18,20,28
Thanks!
With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));
Try it here.
Use following php code:
$temp = array();
foreach($data as $k=>$v){
if(is_array($v)){
foreach($v as $key=>$value){
$temp[] = $value;
}
}
}
echo implode(',',$temp);
Use following code.
$string = '';
foreach($yourarray as $k){
foreach($k as $l){
$string. = $l.",";
}
}
Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
foreach ($subArray as $value) {
$result[] = $value;
}
}
echo implode(',', $result);
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
foreach ($array as $array1) {
echo $array1.'<br>';
}
}
Try this one. It will help you
Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});
Output:
19,18,20,28
This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)
I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));
Output:
19,18,20,28
To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.
try with this..
foreach($data as $dataArr){
foreach ($subArray as $value) {
$res[] = $value;
}
}
echo implode(',', $res);
Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
foreach($subDataArray as $value) {
$values[] = $value;
}
}
$valueString = implode(',', $values);
Edit: Added full solution..

How to create an array of arrays from another array filtering it by a specific key of the subarrays?

I have following array of arrays:
$array = [
[A,a,1,i],
[B,b,2,ii],
[C,c,3,iii],
[D,d,4,iv],
[E,e,5,v]
];
From this one, I would like to create another array where the values are extract only if the value of third key of each subarray is, for example, greater than 3.
I thought in something like that:
if $array['2'] > 3){
$new_array[] = [$array['0'],$array['2'],$array['3']];
}
So in the end we would have following new array (note that first keys of the subarrays were eliminate in the new array):
$new_array = [
[D,4,iv],
[E,5,v]
];
In general, I think it should be made with foreach, but on account of my descripted problem I have no idea how I could do this. Here is what I've tried:
foreach($array as $value){
foreach($value as $k => $v){
if($k['2'] > 3){
$new_array[] = [$v['0'], $v['2'], $v['3']];
}
}
}
But probably there's a native function of PHP that can handle it, isn't there?
Many thanks for your help!!!
Suggest you to use array_map() & array_filter(). Example:
$array = [
['A','a',1,'i'],
['B','b',2,'ii'],
['C','c',3,'iii'],
['D','d',4,'iv'],
['E','e',5,'v']
];
$newArr = array_filter(array_map(function($v){
if($v[2] > 3) return [$v[0], $v[2], $v[3]];
}, $array));
print '<pre>';
print_r($newArr);
print '</pre>';
Reference:
array_map()
array_filter()
In the first foreach, $v is the array you want to test and copy.
You want to test $v[2] and check if it match your condition.
$new_array = [];
foreach($array as $v) {
if($v[2] > 3) {
$new_array[] = [$v[0], $v[2], $v[3]];
}
}

php - how do I display items from an array with their values

I have this array:
Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)
How do i display it like this on a page? (preferably in value descending order as below):
\#cafc (2), #LFC (1), #SkySports (1)
Thanks
First, sort the array
arsort($arrayName);
Next, iterate througth the array keys and values.
foreach($arrayName as $key => $value)
{
echo "$key ($value),";
}
Try using arsort to sort by descending value and then looping through the array, printing key/value pairs, as follows:
arsort($original_array);
foreach($original_array as $k => $v) {
echo $k.'('.$v.')';
}
if i got your question right, use a foreach loop in combination with arsort:
arsort($array);
foreach($array as $k => $v) {
printf('%s (%s)',
htmlspecialchars($k),
htmlspecialchars($v));
}
arsort($array);
$output = array();
foreach($array as $k => $v) {
$output[] = "$k ($v)";
}
print implode(", ", $output);
this will sort the array in reverse order, then create a new array with the data formatted the way you like, then implodes the output into a string separated by commas. The other answers so far will leave a dangling comma.

Categories