How to add comma between elements of array [duplicate] - php

This question already has answers here:
How to implode subarrays in a 2-dimensional array?
(4 answers)
Closed 5 years ago.
everyone.
I have an output of multidimensional array(WRONG):
[ [23], [145], [16], [2], [2], [3], [], ]
I need to have an output like this(GOOD):
[ [2,3], [1,4,5], [1,6], [2], [2], [3], [], ]
Here's array of my data: Array ( [0] => Array ( [0] => 2 [1] => 3 ) [1] => Array ( [0] => 1 [1] => 4 [2] => 5 ) [2] => Array ( [0] => 1 [1] => 6 ) [3] => Array ( [0] => 2 ) [4] => Array ( [0] => 2 ) [5] => Array ( [0] => 3 ) [6] => Array ( ) )
The way I'm trying to do that:
print_r($gretimumosarasas);
echo "[ ";
for ($row = 0; $row < count($gretimumosarasas); $row++) {
echo "[";
for ($col = 0; $col < count($gretimumosarasas[$row]); $col++) {
echo $gretimumosarasas[$row][$col];
}
echo "], ";
}
echo " ]";
Can someone please explain, how to add comma like I wrote an output example below?
If there only way to add coma in second for loop and then search for last symbol index and delete it?
THANK YOU.

While I am extremely nervous of the fact you appear to generating code from your code (here be dragons!) its simple enough.
function array_formatter($arr)
{
$temp=array();
foreach ($arr as $v) {
$temp[] = is_array($v) ? array_formatter($v) : $v;
}
return '[' . implode(',', $temp) . ']';
}
BTW PHP arrays are not multi-dimensional, they are nested. Nested arrays can emulate multi-dimensional arrays, but your example data is not multi-dimensional itself.

Related

Two dimentional array into single dimentional array without foreach PHP [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 4 years ago.
Is there way to convert two dimentional array into single dimentional array without using foreach loop in php.
Below is the actual array
Array
(
[0] => Array
(
[male] => male
[female] => female
)
[1] => Array
(
[male] => male1
[female] => female1
)
)
And Output will be like
Array
(
[0] = > male
[1] = > female
[2] = > male1
[3] = > female1
)
You can use reduce and use array_merge
$array = array( ... ); //Your array here
$result = array_reduce($array, function($c,$v){
return array_merge(array_values($c),array_values($v));
}, array());
This will result to:
Array
(
[0] => male
[1] => female
[2] => male1
[3] => female1
)
This loops through your multidimensional array and stores the results in the new array variable $newArray.
$newArray = array();
foreach($multi as $array) {
foreach($array as $k=>$v) {
$newArray[$k] = $v;
}
}

Merging two associative arrays [duplicate]

This question already has answers here:
Restructure multidimensional array of column data into multidimensional array of row data [duplicate]
(3 answers)
Closed 5 years ago.
I have two arrays.
$a=array('caption'=>array('c one','c two'));
$b=array('photos'=>array('photo one','photo two'));
I want to merge into
Array (
[0] => Array (
[caption] => c one
[file] => photo one
)
[1] => Array (
[caption] => c two
[file] => photo two
)
)
or merge into
Array (
[0] => Array (
[0] => c one
[1] => photo one
)
[1] => Array (
[0] => c two
[1] => photo two
)
)
How do you do it?
The last case can be done by array_map function
$res = array_map(null, $a['caption'], $b['photos']);
demo
You can use a nested loop, and just keep track of your keys.
foreach ([$a, $b] as $array) {
foreach ($array as $text_key => $values) {
foreach ($values as $numeric_key => $value) {
$result[$numeric_key][$text_key] = $value;
}
}
}
If the arrays does not have more in common than the key values then this should work.
It loops one array and uses the key to grab the value from the other array.
$a=array('caption'=>array('c one','c two'));
$b=array('photos'=>array('photo one','photo two'));
Foreach($a['caption'] as $key => $capt){
$new[$key]['caption'] = $capt;
$new[$key]['photos'] = $b['photos'][$key];
}
Var_dump($new);
Output:
array(2) {
[0] => array(2) {
["caption"] => "c one"
["photos"] => "photo one"
}
[1] => array(2) {
["caption"] => "c two"
["photos"] => "photo two"
}
}
https://3v4l.org/kfsft

How to create a permutation of two dimensional array [duplicate]

This question already has answers here:
Finding cartesian product with PHP associative arrays
(10 answers)
Closed 7 years ago.
Initially, I am afraid, that I do not find a better title for this question.
I have a two dimensional array that looks like this, for example:
[0] => Array
(
[0] => 10,00
)
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => true
[1] => false
)
i'd like now to convert/parse this into a two dimensional array that looks like this:
[0] => Array
(
[0] => 10,00
[1] => 3
[2] => true
)
[1] => Array
(
[0] => 10,00
[1] => 4
[2] => true
)
[2] => Array
(
[0] => 10,00
[1] => 3
[2] => false
)
[3] => Array
(
[0] => 10,00
[1] => 4
[2] => false
)
i hope you see, that the result should provide all sort of possible combinations. indeed, the length of the first array can differ.
i'd be interested in how to solve this algorithmically, but at the moment i have no idea.
i am not sure, if this is as easy as it looks like. thank you in advance.
I imagine this could be refined, but it should do the trick:
<?php
$arrStart = array(
array('10,00'),
array(3, 4),
array('true', 'false')
);
$arrPositions = array();
$arrResult = array();
//get a starting position set for each sub array
for ($i = 0; $i < count($arrStart); $i++)
$arrPositions[] = 0;
//repeat until we've run out of items in $arrStart[0]
while (array_key_exists($arrPositions[0], $arrStart[0])) {
$arrTemp = array();
$blSuccess = true;
//go through each of the first array levels
for ($i = 0; $i < count($arrStart); $i++) {
//is there a item in the position we want in the current array?
if (array_key_exists($arrPositions[$i], $arrStart[$i])) {
//add that item to our temp array
$arrTemp[] = $arrStart[$i][$arrPositions[$i]];
} else {
//reset this position, and raise the one to the left
$arrPositions[$i] = 0;
$arrPositions[$i - 1]++;
$blSuccess = false;
}
}
//this one failed due to there not being an item where we wanted, skip to next go
if (!$blSuccess) continue;
//successfully adding nex line, increase the right hand count for the next one
$arrPositions[count($arrStart) - 1]++;
//add our latest temp array to the result
$arrResult[] = $arrTemp;
}
print_r($arrResult);
?>

PHP use of array_map array_shift to slice array into odd and even sub arrays

By definition, PHP's array_shift will return the first elem from the array and the array will downsize one.
I want to slice an array alternatingly into two sub-arrays, i.e index of 0,2,4,6,... and index of 1,3,5,7,...
I first break it into chunks of 2, then I use array_map to call array_shift. However, it is half correct (output below):
array1: Array ( [0] => greeting [1] => question [2] => response )
array2: Array ( [0] => Array ( [0] => greeting [1] => hello ) [1] => Array ( [0] => question [1] => how-are-you ) [2] => Array ( [0] => response [1] => im-fine ) )
Here's the code:
$a=array("greeting", "hello", "question", "how-are-you", "response", "im-fine");
$b=array_chunk($a, 2);
$c=array_map("array_shift", $b);
echo "array1: ";
print_r($c);
echo "array2: ";
print_r($b);
array2 does not seem to downsize after array_shift. Is this the correct behavior? How can I do what I intend to do?
Thanks
While this is already solved using array functions here is a low tech solution using a simple toggle to separate the odd and even elements...
$in = array("greeting", "hello", "question", "how-are-you", "response", "im-fine");
$i = 0;
$list = array();
foreach ($in as $text)
{
$list[$i][] = $text;
$i = 1 - $i;
}
print_r($list[0]);
print_r($list[1]);
Result...
Array ( [0] => greeting [1] => question [2] => response )
Array ( [0] => hello [1] => how-are-you [2] => im-fine )
Try this way to split your array alternatively EVEN and ODD keys, there may be many ways to do this, but this is my simple way using array_walk
$odd = [];
$even = [];
$both = [&$even, &$odd];
$array=["greeting", "hello", "question", "how-are-you", "response", "im-fine"];
array_walk($array, function($value, $key) use ($both) { $both[$key % 2][] = $value; });
print '<pre>';
print_r($even);
print_r($odd);
print '</pre>';
RESULT:
Success time: 0.02 memory: 24448 signal:0
<pre>Array
(
[0] => greeting
[1] => question
[2] => response
)
Array
(
[0] => hello
[1] => how-are-you
[2] => im-fine
)

Concatenate values of two arrays [duplicate]

This question already has answers here:
Cartesian Product of N arrays
(10 answers)
Closed 8 years ago.
Let's assume I have an two arrays and I want to merge every value with the other value of the array.
Array 1
array (size=2)
0 => 1
1 => 2
Array 2
array (size=2)
0 => 3
1 => 4
Wanted result array / string:
array (size=4)
0 => '1,3'
1 => '1,4'
2 => '2,3'
3 => '2,4'
I can't get my head around it. Obviously I would need to merge every one array key/value with the other ones. Is there a more elegant way then doing this in a while/foreach loop?
You need a foreach loop inside a foreach loop. (Actualy, you will have to loop through both arrays to get a concatenated product of both arrays, you don't actually need two foreach loops). You could mix: whiles, foreach, for, or php filter/intersect array functions
Example
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = $item1.','.$item2;
}
}
https://eval.in/215001
your result array Length will be array1.Length * array2.Length
2d arrays
You could also put an array inside an array like this:
$array1 = array(1,2);
$array2 = array(3,4);
$result = array();
foreach ($array1 as $item1){
foreach($array2 as $item2){
$result[] = array($item1, $item2);
}
}
//$result[0][0] = 1 -- $result[0][1] = 3
//$result[1][0] = 1 -- $result[1][1] = 4
//$result[2][0] = 2 -- $result[2][1] = 3
//$result[3][0] = 2 -- $result[3][1] = 4
We call this a 2d (2 dimensional) array, because you could grapicly display this as a grid, like displayed here above. If you would put an Array, inside an Array inside an Array, you would call this a 3 dimensional array, etc.
print_r($result); in php:
Array
(
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 1
[1] => 4
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 2
[1] => 4
)
)
try
$a= array ('0' => 1,'1' => 2);
$b= array ('0' => 3,'1' => 4);
for($i=0; $i<count($a); $i++) {
for($j=0; $j<count($b); $j++) {
$newarr[]= $a[$i].','.$b[$j];
}
}
print_r($newarr);//Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )
$a=array('1','2');
$b=array('3','4');
$res=array();
for($i=0;$i<count($a);$i++)
{
foreach($b as $bb)
{
$res[]=strval($a[$i].','.$bb);
}
}
print_r($res);//output=Array ( [0] => 1,3 [1] => 1,4 [2] => 2,3 [3] => 2,4 )

Categories