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);
Related
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.
I have a multiple level array field need to be submit via a form. Not sure what will be the easiest solution:
As php will auto convert dot to underscore, so i change it to array:
$form['a.b_b.c'] ==> <input name="a[b_b][c]" value="$form[a.b_b.c]">
And I got $_POST[a][b_b][c] correctly.
But what is the easiest way to assign this $_POST value back to the original $form['a.b_b.c'] without much loops? eg
$form['a.b_b.c'] = $_POST['a']['b_b']['c'];
Or is there a better way to walk around?
very close to this question but still not yet:
Convert dot syntax like "this.that.other" to multi-dimensional array in PHP
And here is my current solution:
foreach ($form as $k) {
$form[$k] = assign_val($_POST, $k);
}
function assign_val($arr = [], $key = '') {
$keys = explode('.', $key);
$val = &$arr;
foreach ($keys as $k) {
$val = &$val[$k];
}
return $val;
}
I would have a function flatten and do something like:
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
And then you can do:
$form = flatten($_POST);
I have an array like that
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
and i want to achieve array like that
$arrProducts= array(array('product_id'=>354,'qty'=>1),array('product_id'=>375,'qty'=>1),array('product_id'=>344,'qty'=>2));
I achieved this array using this code
foreach($products as $val)
{
$abc[] =$val[0];
}
for($i=0;$i<count($abc);$i++)
{
if($i%2==0)
{
$newarr[]['product_id'] = $abc[$i];
}
else{
$newarr[]['qty'] = $abc[$i];
}
}
for($j=0;$j<count($newarr);$j++)
{
if($j%2==0)
{
$arrProducts[] = array_merge($newarr[$j],$newarr[$j+1]);
}
else{
continue;
}
}
echo '<pre>';
print_r($arrProducts);
but i think my way to get this array is too long so how can i get this array in short way using some array functions or should i use this code?
You can use array_chunk in this case if this is always by twos, and combine it with array_combine():
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$products = array_chunk($products, 2);
$arrProducts = array();
$keys = array('product_id', 'qty');
foreach($products as $val) {
$arrProducts[] = array_combine($keys, array(reset($val[0]), reset($val[1])));
}
echo '<pre>';
print_r($arrProducts);
Another alternative would be:
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$keys = array('product_id', 'qty');
$arrProducts = array_map(function($e) use ($keys) {
return array_combine($keys, array_map('reset', $e));
}, array_chunk($products, 2));
This will yield the same result.
Consume two array elements on each iteration:
$arrProducts = array();
$inputLength = count($products);
for ($i = 0; $i < $inputLength; $i += 2) {
$arrProducts[] = array('product_id' => $products[$i][0], 'qty' => $products[$i+1][0]);
}
$i=1;
$j=0;
foreach($products as $val)
{
if(($i%2) == 0)
{
$abc[$j]['qty'] =$val[0];
$j++;
}
else
{
$abc[$j]['product_id'] =$val[0];
}
$i++;
}
Is there a simple way to take a single-dimensional array and convert it to a multi-dimensional array based on the spaces, or any character(s), in the keys?
$arr['foo1'] = 'bar1';
$arr['foo2'] = 'bar2';
$arr['foo3 tier1' ] = 'bar3';
$arr['foo4 tier1' ] = 'bar4';
and turn it into
$arr['foo1'] = 'bar1';
$arr['foo2'] = 'bar2';
$arr['foo3']['tier1'] = 'bar3';
$arr['foo4']['tier1'] = 'bar4';
you can always do some sort of foreach loop
$newarr = array();
foreach ($arr as $key => $value) {
$output = explode(' ',$key,2);
if(count($output)) {
$newarr[$output[0]][$output[1]] = $value;
} else {
$newarr[$key] = $value;
}
}
That code will only work for one space but you can expand it to multiple spaces, something like
function pivot($arr,$delimeter) {
$return = array();
foreach ($arr as $key => $value) {
$output = explode($delimeter,$key,2);
if(count($output)) {
if(strpos($output[1],$delimeter) > 0) {
$return[$output[0]] = pivot(array($output[1]=>$value),$delimeter);
} else {
$return[$output[0]][$output[1]] = $value;
}
} else {
$return[$key] = $value;
}
}
return $return;
}
Whats the easiest way to invert a multidimensional array. By invert I mean similar to array_flip.
e.g
[0][5][var_name] = data
[0][3][var_name2] = data2
[1][var_name3] = data3
[0][1][4][var_name4] = data4
inverted would be:
[var_name][0][5] = data
[var_name2][0][3] = data2
[var_name3][1] = data3
[var_name4][0][1][4] = data4
Any ideas?
You could store a list of the keys of all ancestors and when you hit a "leaf" use this list to create the "flipped" version.
<?php
$data = array(
0=>array(
5=>array('var_name' => 'data'),
3=>array('var_name2' => 'data2'),
1=>array(4=>array('var_name4'=>'data4'))
),
1=>array('var_name3'=>'data3')
);
$result = array();
foo($data, $result);
($result['var_name'][0][5] === 'data') or die('1');
($result['var_name2'][0][3] === 'data2') or die('2');
($result['var_name3'][1] === 'data3') or die('3');
($result['var_name4'][0][1][4] === 'data4') or die('4');
echo 'ok';
function foo(array $a, array &$target, $stack=array()) {
foreach($a as $key=>$value) {
if ( is_array($value) ) {
array_push($stack, $key);
foo($value, $target, $stack);
array_pop($stack);
}
else {
$target[$key] = array();
$tmp = &$target[$key];
foreach( $stack as $s ) { // now it's not so stack-ish anymore :-S
$tmp[$s] = array();
$tmp = &$tmp[$s];
}
$tmp = $value;
}
}
}
I couldn't think of an easy way to do this. So I wrote up a really complicated way to do it. Namely:
Take the multidimensional array and flatten it into a list of keys and values.
Reverse the keys.
Unflatten the list to obtain an inverted multidimensional array.
Code
<?php
function print_entries($array, $prekeys = array())
{
foreach ($array as $key => $value)
{
$keys = array_merge($prekeys, array($key));
if (is_array($value))
print_entries($value, $keys);
else
echo '[' . implode('][', $keys) . "] = $value\n";
}
}
function flatten_array($array)
{
$entries = array();
foreach ($array as $key => $value)
{
if (is_array($value))
{
foreach (flatten_array($value) as $subentry)
{
$subkeys = $subentry[0];
$subvalue = $subentry[1];
$entries[] = array(array_merge(array($key), $subkeys), $subvalue);
}
}
else
$entries[] = array(array($key), $value);
}
return $entries;
}
function unflatten_array($entries)
{
$array = array();
foreach ($entries as $entry)
{
$keys = $entry[0];
$value = $entry[1];
$subarray = &$array;
foreach ($keys as $i => $key)
{
if ($i < count($keys) - 1)
{
if (!isset($subarray[$key]))
$subarray[$key] = array();
$subarray = &$subarray[$key];
}
else
$subarray[$key] = $value;
}
}
return $array;
}
function invert_array($array)
{
$entries = flatten_array($array);
foreach ($entries as &$entry)
$entry[0] = array_reverse($entry[0]);
return unflatten_array($entries);
}
$array = array
(
0 => array
(
5 => array('var_name' => 'data'),
3 => array('var_name2' => 'data2'),
1 => array(4 => array('var_name4' => 'data4'))
),
1 => array(0 => array('var_name' => 'data3'))
);
print_entries($array);
echo "\n";
print_entries(invert_array($array));
?>
Output
[0][5][var_name] = data
[0][3][var_name2] = data2
[0][1][4][var_name4] = data4
[1][0][var_name] = data3
[var_name][5][0] = data
[var_name2][3][0] = data2
[var_name4][4][1][0] = data4
[var_name][0][1] = data3
Edit: I noticed now that you don't reverse the keys but you simply move the var_name portion from the end to the front and leave the numerical indices alone. It's easy enough to modify the line in flatten_array where I call array_reverse to re-order the keys in a different way. The core flatten/unflatten logic would not need to be changed. I leave this as an exercise for the reader. :-)