implode multidimensional array - php

while($row=mysql_fetch_assoc($query)) {
$id = $row['id'];
$col1 = $row['name1'];
$col2= $row['name2'];
$col3= $row['name3'];
${"$id"} = array("$col1","$col2","$col3");
${"$s".$i}[] = ${"$id"};
}
This is just a breif example of what i'm trying to accomplish, $i is incremented somewhere else. I'm trying to implode the arrays in the array. So below I have imploded the main array but how do I implode the other arrays?
for($i=0;$i<11;$i++) {
$array = ${"s" . $i};
$outcomes = implode("",$array); //implodes main array
}

Not quite sure what you are trying to achieve here, but does this help?
function recursive_echo ($arr, $spacing = 0) {
$padding = ($spacing) ? str_pad('', $spacing) : '';
foreach ($arr as $key => $val) {
if (is_array($val)) {
echo "{$padding}{$key}:<br />\n";
recursive_echo($val, $spacing + 2);
} else {
echo "{$padding}{$val}<br />\n";
}
}
}
This function just echoes out the data, but it illustrates how to recurse through a multi-dimensional array where the number of dimensions is unknown.

Related

Expand an associative array N-times and get all key combinations

I am trying to expand/multiply an associative array N times and get all possible key combinations.
To do it manually for two times, I would do this:
$copy = $array;
foreach ($array as $key1=>$tmp1) {
foreach ($copy as $key2=>$tmp2) {
$combos[] = array($key1,$key2);
}
}
for expanding three times:
$copy = $copy2 = $arr1;
foreach ($arr1 as $key1=>$qd1) {
foreach ($copy as $key2=>$qd2) {
foreach ($copy2 as $key3=>$qd3) {
$combos[] = array($key1,$key2,$key3);
}
}
}
how would one do this for n-times? $combos should have n-elements for each element as shown.
I looked at the other questions, but it is not quite the same here.
Finally got it:
$array = ['1' => [3, 4], '2' => [5, 6]];
$depth = 2;
function florg ($n, $elems) {
if ($n > 0) {
$tmp_set = array();
$res = florg($n-1, $elems);
foreach ($res as $ce) {
foreach ($elems as $e) {
array_push($tmp_set, $ce . $e);
}
}
return $tmp_set;
}
else {
return array('');
}
}
$output = florg($depth, array_keys($array));
What I did is basically extract the first level keys with array_keys and then created all possibles combinations thanks to https://stackoverflow.com/a/19067650/4585634.
Here's a working demo: http://sandbox.onlinephpfunctions.com/code/94c74e7e275118cf7c7f2b7fa018635773482fd5
Edit: didn't see David Winder comment, but that's basically the idea.

Merging associative array with same values?

I have an associative array -
{
"1":{"list_price_9":"1250.0000","list_price_18":"1250.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"2":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"3":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"4":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"5":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"6":{"list_price_9":"2500.0000","list_price_18":"2500.0000","golflan_price_9":"0.0000","golflan_price_18":"2500.0000"},
"7":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"2500.0000"}
}
I want to convert the array such that the resulting array has merged the keys with similar values in a comma separated string.
So the result will be something like this -
{
"1":{"list_price_9":"1250.0000","list_price_18":"1250.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"2,3,4,5,7":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"6":{"list_price_9":"2500.0000","list_price_18":"2500.0000","golflan_price_9":"0.0000","golflan_price_18":"2500.0000"}
}
This seems simple, but I am not being able to come up with an elegant solution for this.
Kindly help.
I tried something like this -
$common_prices = array();
foreach ($pricelist as $day => $prices) {
foreach ($common_prices as $new_day => $new_prices) {
if($prices === $new_prices) {
$modified_day = $new_day.','.$day;
$common_prices[$modified_day] = $new_prices;
unset($new_day);
}
}
$common_prices[$day] = $prices;
}
where $pricelist is the given array and $common_prices is the expected array. But obviously this will not work.
You can do it with linear complexity using intermediate array of accumulated keys for unique values:
$keys = [];
foreach($pricelist as $key=>$val) {
$str = json_encode($val);
if(!isset($keys[$str])) {
$keys[$str] = [];
}
$keys[$str][] = $key;
}
$common_prices = [];
foreach($keys as $key=>$val) {
$common_prices[join(',',$val)] = json_decode($key);
}
You can just aggregate keys and data in the separated arrays and then combine them.
Example:
$keys = [];
$data = [];
foreach ($pricelist as $day => $prices) {
if ($key = array_search($prices, $data))
$keys[$key] .= ',' . $day;
else {
$keys[] = $day;
$data[] = $prices;
}
}
$common_prices = array_combine($keys, $data);

Convert multidimensional array keys to string

I have a multidimensional array like this:
$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';
And another array like:
$array2['second-first']='newvalue21';
$array2['second-third-first']='newvalue231';
And I can't get the way to walk $array1 recursively to check, in each iteration, if exist any element in $array2 with a key equivalent to the current element key and their parents converted to string.
To simplify the question, I will have enough with a function that prints something like:
// walking $array1:
first
second-first
second-second
second-third-first
second-fourth
third
Thank you.
Solution based on Clément Malet answer
function print_array_reccur ($array1, $array2, $str = '')
{
foreach ($array1 as $key => $val) {
if (is_array($val)) {
if ($str == '') {
print_array_reccur($val, $array2, $key);
} else {
print_array_reccur($val, $array2, $str . '-' . $key);
}
} else {
if ($str == '') {
$result = $key;
} else {
$result = $str . '-' . $key;
}
if(isset($array2[$result]))
{
echo 'Found $array2['.$result.'] = ' . $array2[$result] . "\n";
}
}
}
}
print_array_reccur ($array1, $array2);
/* OUTPUT:
Found $array2[second-first] = newvalue21
Found $array2[second-third-first] = newvalue231
*/
I really didn't understand what you wanted in the very end, and what you want to achieve later on with your second array.
But since you are looking for a way to print something (glad you simplified that way), here it is :
$array1['first']='myvalue1';
$array1['second']=array();
$array1['second']['first']='myvalue21';
$array1['second']['second']='myvalue22';
$array1['second']['third']=array();
$array1['second']['third']['first']='myvalue231';
$array1['second']['fourth']='myvalue24';
$array1['third']='myvalue3';
function print_array_reccur ($array, $str = '') {
foreach ($array as $key => $val) {
if (is_array($val)) {
if ($str == '') {
print_array_reccur($val, $key);
} else {
print_array_reccur($val, $str . '-' . $key);
}
} else {
if ($str == '') {
echo $key . "\n";
} else {
echo $str . '-' . $key . "\n";
}
}
}
}
print_array_reccur ($array1);
Output :
first
second-first
second-second
second-third-first
second-fourth
third

Implode() array and make new line after two elements

I am looking to echo comma separated elements of an array e.g:
Element1, Element2, Element3, Element4, Element5, Element6
However, for the purposes of keeping the echoed elements neat, I might need to go to a new line after the each second element of each line e.g
Element1, Element2,
Element3, Element4,
Element5, Element6
As is I am doing:
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
echo implode(' ,', $labels_array);
?>
And obviously getting:
Element1, Element2, Element3, Element4, Element5, Element6
How then do i do a newline after each second element of a line using implode() or otherwise?
<?php
$labels = array('Element1', 'Element2', 'Element3', 'Element4', 'Element5', 'Element6');
# Put them into pairs
$pairs_array = array_chunk($labels, 2);
# Use array_map with custom function
function joinTwoStrings($one_pair) {
return $one_pair[0] . ', ' . $one_pair[1];
}
$pairs_array = array_map('joinTwoStrings', $pairs_array);
echo implode(',' . PHP_EOL, $pairs_array);
You can use foreach to achive it, im pasting code for you which will give you your desired output
<?php
$labels = array("Element1", "Element2", "Element3", "Element4", "Element5","Element6");
$key = 1;
$lastkey = sizeof($labels);
foreach($labels as $value)
{
if($key%2)
{
if($key==$lastkey)
{
echo $value;
}
else
{
echo $value.",</br>";
}
}
else
{
if($key==$lastkey)
{
echo $value."</br>";
}
else
{
echo $value.",</br>";
}
}
$key++;
}
?>
untested, but something like this should work
$i = 1;
foreach($labels as $label) {
echo $label;
// add a comma if the label is not the last
if($i < count($labels)) {
echo ", ";
}
// $i%2 is 0 when $i is even
if($i%2==0) {
echo "<br>"; // or echo "\n";
}
$i++;
}
For the sake of fancy:
$labels_array=array("Element 1","Element 2","Element 3","Element 4","Element 5","Element 6");
echo implode(",\n",array_map(function($i){ // change to ",<br />" for HTML output
return implode(", ",$i);
},array_chunk($labels_array,2)));
Online demo
<?php
$labels = Requisitions::getLabelNames($id);
foreach($labels as $label) {
$labels_array[] = $label['name'];
}
for($i=0;$i<count($labels_array);$i++)
{ echo($labels_array[$i]);
if($i % 2 != 0)
{
echo("\n");
}else{echo(",");}
}
?>
$i = 1;
$str = '';
foreach($labels AS $label)
{
$str += "$label, ";
if ($i % 2 == 0)
{
$str += "\n";
}
$i++;
}
//Remove last 2 chars
$str = substr($str,0,(strlen($str)-2));
Unless you need the array for something else, this just builds the string...
<?php
$labels = Requisitions::getLabelNames($id);
$s='';
$i=0;
$l=count($labels);
foreach($labels as $label){
$s.=$label['name'];
// Append delimeter. Makes sure every second, and the last one, will be a line break
$s.=((++$i%2)&&($l!=$i))?' ,':"\n";
}
echo $s;
?>
If you do need the array for something, create it first and modify above as needed.

Process array starting with second entry?

I have an array in PHP and would like to use foreach to process entries skipping [0], to process [1], [2], etc.
Thank you
you can use array_slice
$array = array(1,2,3);
foreach (array_slice($array,1) as $value ) {
echo $value;
}
If you don't mind losing first element you can use array_shift
array_shift($array);
foreach ( $array as $value ) {
echo $value;
}
Output
23
$i = 0;
foreach ($ar as $value) {
if ($i > 0) {
// code here
}
$i++;
}
You can keep a variable for this:
$firstSkipped = false;
foreach ($arr as $value) {
if (!$firstSkipped) {
$firstSkipped = true;
continue;
}
// code here
}
Or you could just use a regular for loop, setting the beginning counter to 1:
for ($i = 1, $count = count($arr); $i < $count; $i++) {
// code here
}
You can remove the first entry from an array with array_shift.
$array = array("a","b","c");
array_shift($array);
foreach ($array as $values)
{
echo $values; //bc
}
Try this:
$arr = array(0,1,2,3,4,5);
unset($arr[0]);
foreach($arr as $value) {
echo $value;
echo "<br />";
}
This would delete first entry from array, so it would not skip as you asked, but anyway you can try this...

Categories