How to transform array to this json pattern? - php

I have array something like this
Array
(
[0] => Array
(
[product_id] => 13
[unit] => 1
[price] => 20.0000
[total] => 20.0000
)
[1] => Array
(
[product_id] => 15
[unit] => 2
[price] => 30.0000
[total] => 10.0000
)
)
I was stuck to transform above array to the "ProductList" in the following pattern
array(
"UserID" => 2,
"ProductList" => [
{
"ProductID"=> 13,
"Price"=> 20.0000
},
{
"ProductID"=> 15,
"Price"=> 30.0000
}
]
)
I tried like this:
$products = [];
foreach($items as $item) {
if(!empty($item['product_id'])) {
$product = '{"ProductID"=>' . $item['product_id'] . '}';
$products[] = $product;
}
}
But not the expected result.

You're looking for json_encode(): http://php.net/manual/en/function.json-encode.php
Assign your array to a variable, for example $products, and then you can simply write json_encode($products) to achieve your desired result.

Try this,
$prodlist = array();
$x = 0;
foreach($arrs as $arr) {
//if ($arr['product_id'] == "" && $arr['price'] == "") continue;
$prodlist[$x]['Price'] = $arr['price'];
$prodlist[$x]['ProductID'] = $arr['product_id'];
$x += 1;
}
$arr2return['user_id'] = $user_id;
$arr2return['ProductList'] = $prodlist;
json_encode($arr2return);

Related

how to get array with unique values in laravel/php

I need to merge arrays into 1 array but what I need is to remove before the main data they b oth have in common (duplicated values i mean), I need only unique values when merged.
array formed from foreach.
public $arrayfields= [];
public $itemMap = [];
public function getRowMapping(array $row,$uniqueField,$moduleName)
{
$arrayData = [];
foreach ($this->columnMapping as $key => $value) {
$row = $this->moduleType($key,$value,$row,$moduleName);
}
$unique = $row[$uniqueField];
if(!isset($this->itemMap[$unique])){
$this->itemMap[$unique] = $row;
$this->itemMap[$unique][$unique]['items'] = [];
}
$this->itemMap[$unique]['items'][] = $row['items'];
return $row;
}
i changed little bit to my input
How can i do that?
so now the input will be like this
Array
(
[bill_type] => 1
[bill_number] => BIL-003
[order_number] => ON-003
[items] => Array
(
[track_inventory] => 0
[sku1] => sku1
[name] => Kidswear1
)
)
Array
(
[bill_type] => 1
[bill_number] => BIL-003
[order_number] => ON-003
[items] => Array
(
[track_inventory] => 0
[sku1] => sku2
[name] => Pant
)
)
Array
(
[bill_type] => 1
[bill_number] => BIL-002
[order_number] => ON-002
[items] => Array
(
[track_inventory] => 0
[sku1] => sku3
[name] => Pants
)
)
The final output I'm looking for is
Array
(
[BIL-003] => Array
(
[bill_type] => 1
[order_number] => ON-003
[items] => Array
(
[0] => Array(
[track_inventory] => 0
[sku1] => sku1
[name] => Kidswear1
)
[1] => Array
(
[track_inventory] => 0
[sku1] => sku2
[name] => Pant
)
)
[BIL-002] => Array
(
[bill_type] => 1
[order_number] => ON-002
[items] => Array
(
[0] => Array(
[track_inventory] => 0
[sku1] => sku3
[name] => pants
)
)
)~~~
I think there is no standard library function to accomplish this.
So here is the function that accomplishes this:
function merge($array1, $array2)
{
$arraymerged = [];
if (is_array($array1) && is_array($array2)) {
//collect the keys of two arrays
$keys = [];
foreach ($array1 as $key => $value) {
$keys[$key] = true;
}
foreach ($array2 as $key => $value) {
$keys[$key] = true;
}
//merge key values for each key
foreach ($keys as $key => $value) {
if (isset($array1[$key]) && isset($array2[$key])) {
if ($array1[$key] == $array2[$key]) {
$arraymerged[$key] = $array1[$key];
} else {
$arraymerged[$key] = [$array1[$key], $array2[$key]];
}
} else if (isset($array1[$key]))
$arraymerged[$key] = $array1[$key];
else
$arraymerged[$key] = $array2[$key];
}
return $arraymerged;
}
}
Here is my suggestion,
if the input is array, check my answer on this post Convert an associative array into an associative array which has a key with another associative array as its value in php
otherwise check below code.
bill_number as unique key and run foreach and append items array elements.
let me give you an example
$arr1 = [
"bill_type" => 1,
"bill_number" => 'BIL-003',
"items"=>[
0 => [
"name"=>"test"
]
]
];
$arr2 = [
"bill_type" => 1,
"bill_number" => 'BIL-003',
"items"=>[
0 => [
"name"=>"test_2"
]
]
];
$formattedArr = [];
//merge these arrays
$combinedArr = [];
$combinedArr[] = $arr1;
$combinedArr[] = $arr2;
foreach($combinedArr as $key=>$value){
$formattedArr[$value['bill_number']]["bill_type"] = $value["bill_type"];
$formattedArr[$value['bill_number']]["items"][] = $value["items"];
}
print_r($formattedArr);
I haven't tested this code, but i think this will be ans to your question.
<?php
$a1 = array(
"bill_type" => "1",
"bill_number" => "BIL-003",
"order_number" => "ON-003",
"items" => array(
"track_inventory" => "0",
"sku1" => "sku1",
"name" => "Kidswear1"
)
);
$a2 = array(
"bill_type" => "1",
"bill_number" => "BIL-003",
"order_number" => "ON-003",
"items" => array(
"track_inventory" => "0",
"sku1" => "sku2",
"name" => "Pant"
)
);
$result = function ($a1, $a2) {
$b1 = $a1['items'];
$b2 = $a2['items'];
$c1 = $a1;
$c2 = $a2;
unset($c1['items']);
unset($c2['items']);
if (count(array_diff($c1, $c2)) == 0) {
if (count(array_diff($b1, $b2)) != 0) {
$c1['items'] = [$b1, $b2];
} else {
$c1['items'] = $b1;
}
return $c1;
}else{
//you should complete this part by yourself, if first parts are not equal.
}
return $c1;
};
$r = $result($a1, $a2);
var_dump($r);
result:
(array) [4 elements]
bill_type: (string) "1"
bill_number: (string) "BIL-003"
order_number: (string) "ON-003"
items:
(array) [2 elements]
0:
(array) [3 elements]
track_inventory: (string) "0"
sku1: (string) "sku1"
name: (string) "Kidswear1"
1:
(array) [3 elements]
track_inventory: (string) "0"
sku1: (string) "sku2"
name: (string) "Pant"

PHP - Convert a Single Array into a Multidimensional Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm newbie in PHP.
I need send data for API purpose.
I have array print_r($detail) like this
Array
(
[0] => Array
(
[id] => item1
)
[1] => Array
(
[price] => 300
)
[2] => Array
(
[quantity] => 1
)
[3] => Array
(
[id] => item2
)
[4] => Array
(
[price] => 400
)
[5] => Array
(
[quantity] => 2
)
)
And I want convert it to multidimensional before sending to another process, like
Array
(
[0] => Array
(
[id] => item1
[price] => 300
[quantity] => 1
)
[1] => Array
(
[id] => item2
[price] => 400
[quantity] => 2
)
)
How it is possible?
You can split your $details array into multiple chunks. I've written the following function which accepts a custom chunk size (note count($initialArray) % $chunkSize === 0 must be true):
function transformArray(array $initialArray, $chunkSize = 3) {
if (count($initialArray) % $chunkSize != 0) {
throw new \Exception('The length of $initialArray must be divisible by ' . $chunkSize);
}
$chunks = array_chunk($initialArray, 3);
$result = [];
foreach ($chunks as $chunk) {
$newItem = [];
foreach ($chunk as $item) {
$newItem[array_keys($item)[0]] = reset($item);
}
$result[] = $newItem;
}
return $result;
}
Given your details array, calling transformArray($details) will result in:
The customizable chunk size allows you to add more data to your source array:
$details = [
['id' => 'item1'],
['price' => 300],
['quantity' => 1],
['anotherProp' => 'some value'],
['id' => 'item2'],
['price' => 400],
['quantity' => 2],
['anotherProp' => 'another value'],
];
The function call is now transformArray($details, 4);:
This version may be with the same result of #PHPglue answer. But this takes only one foreach. I think this is faster, more efficient way as stated here by one of the Top SO Users.
Try to look if you want it.
Live Demo
<?php
function explodeArray($arr)
{
$newArr = array();
foreach($arr as $row)
{
$key = array_keys($row)[0];
$curArr = count($newArr) > 0 ? $newArr[count($newArr)-1] : array();
if( array_key_exists($key, $curArr) )
{
array_push($newArr, array($key=>$row[$key]) );
}
else
{
$index = count($newArr) > 0 ? count($newArr) - 1 : 0 ;
$newArr[$index][$key] = $row[$key];
}
}
return $newArr;
}
Different Arrays for testing.
$detail = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2)
);
var_dump( explodeArray($detail) );
$detail_match = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('newkey'=>'sample'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2),
array('newkey'=>'sample')
);
var_dump( explodeArray($detail_match) ); // Works with any size of keys.
$detail_diff_key = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('diff1'=>'sample1'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2),
array('diff2'=>'sample2')
);
var_dump( explodeArray($detail_diff_key) ); // Works with any size of keys and different keys.
$detail_unmatch = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('unmatchnum'=>'sample1'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2)
);
var_dump( explodeArray($detail_unmatch) );
I think this little block of code work for you.
Use:
$detail = array(
"0" => array("id" => "item1"),
"1" => array("price" => "300"),
"2" => array("quantity" => "1"),
"3" => array("id" => "item2"),
"4" => array("price" => "400"),
"5" => array("quantity" => "2"),
"6" => array("id" => "item3"),
"7" => array("price" => "500"),
"8" => array("quantity" => "3")
);
$i = 0;
$j = 0;
$multi_details = array();
while($j < count($detail)){
$multi_details[$i][id] = $detail[$j++][id];
$multi_details[$i][price] = $detail[$j++][price];
$multi_details[$i][quantity] = $detail[$j++][quantity];
$i++;
}
echo '<pre>';
print_r($multi_details);
echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => item1
[price] => 300
[quantity] => 1
)
[1] => Array
(
[id] => item2
[price] => 400
[quantity] => 2
)
[2] => Array
(
[id] => item3
[price] => 500
[quantity] => 3
)
)
Something like this should do it
$newArray = array();
$newRow = array();
foreach ($array as $row) {
$key = array_keys($row)[0];
$value = array_values($row)[0];
if ($key == 'id') {
$newArray[] = $newRow;
}
$newRow[$key] = $value;
}
$newArray[] = $newRow;
This version looks for repeat keys then creates a new Array whenever they are the same so you could have some different data. Hope it helps.
function customMulti($customArray){
$a = array(); $n = -1; $d;
foreach($customArray as $i => $c){
foreach($c as $k => $v){
if(!isset($d)){
$d = $k;
}
if($k === $d){
$a[++$n] = array();
}
$a[$n][$k] = $v;
}
}
return $a;
}
$wow = customMulti(array(array('id'=>'item1'),array('price'=>300),array('quantity'=>1),array('id'=>'item2'),array('price'=>400),array('quantity'=>2)));
print_r($wow);

How to group keys and values of an (sub)array and sum its values using PHP? [duplicate]

This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 9 months ago.
I have the following array
Array (
[0] => Array
(
[0] => ALFA
[1] => 213
)
[1] => Array
(
[0] => ALFA
[1] => 151
)
[2] => Array
(
[0] => ALFA
[1] => 197
)
[3] => Array
(
[0] => BETA
[1] => 167
)
[4] => Array
(
[0] => ZETA
[1] => 254
)
[5] => Array
(
[0] => GAMA
[1] => 138
)
[6] => Array
(
[0] => GAMA
[1] => 213
)
)
And I would like to group the key[0] of the subarray so I can see how many equal keys it has.
Something like that:
ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2
I tried with array_count_values, but without success.
foreach ($array as $value) {
echo '<pre>';
print_r(array_count_values($value));
echo '</pre>';
}
With that we have following result:
Array
(
[ALFA] => 1
[213] => 1
)
Array
(
[ALFA] => 1
[151] => 1
)
...
Array
(
[GAMA] => 1
[213] => 1
)
And after that I would like to sum the values of each group as well.
ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213
I think that when we solve the first part of the problem, the second would follow easier with quite the same method.
The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:
ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5
This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.
I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.
<?php
$result = array();
foreach ($array as $el) {
if (!array_key_exists($el[0], $result)) {
$result[$el[0]] = array();
}
$result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>
Result:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Solution for you is here:
Code:
$input = [
['alfa', 123],
['alfa', 223],
['alfa', 122],
['alfa', 554],
['alfa', 34],
['dalfa', 123],
['halfa', 223],
['dalfa', 122],
['halfa', 554],
['ralfa', 34]
];
$result = [];
foreach ($input as $node) {
if (isset($result[$node[0]])) {
$result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
} else {
$result[$node[0]] = ['sum' => $node[1], 'count' => 1];
}
}
print_r($result);
foreach ($result as $key => &$data) {
$data = $data['sum'] / $data['count'];
}
print_r($result);
Output:
Array
(
[alfa] => Array
(
[sum] => 1056
[count] => 5
)
[dalfa] => Array
(
[sum] => 245
[count] => 2
)
[halfa] => Array
(
[sum] => 777
[count] => 2
)
[ralfa] => Array
(
[sum] => 34
[count] => 1
)
)
Array
(
[alfa] => 211.2
[dalfa] => 122.5
[halfa] => 388.5
[ralfa] => 34
)
$sort = array();
foreach ($array as $value) {
$sort[$value[0]][] = $value[1];
}
then you count how many keys each has
$keys = array();
foreach($sort as $k => $v) {
$keys[$k] = count($v);
}
then for calculating the amount
$sum = array();
$average = array();
foreach($sort as $k => $v) {
$amount = 0;
foreach($v as $val) {
$amount += $val;
}
$sum[$k] = $amount;
$average[$k] = $amount / $keys[$k];
}
HOWEVER, If you want all the details in one array:
$final = array();
foreach ($array as $value) {
$final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
$final[$k]["amount"] = count($v['values']);
$amount = 0;
foreach($v['values'] as $val) {
$amount += $val;
}
$final[$k]["sum"] = $amount;
$final[$k]["average"] = $amount / $final[$k]["amount"];
}
example: http://jdl-enterprises.co.uk/sof/25789697.php
Includes Output
Just copy the codes to your favorite text editor, sure it works perfectly.
$items = [
['ALFA',213],
['ALFA',151],
['ALFA',197],
['BETA',167],
['ZETA',254],
['GAMA',138],
['GAMA',213]
];
echo '<pre>' . print_r($items,true) . '</pre>';
$result;
foreach ($items as $value) {
# code...
if (isset($result[$value[0]])) {
$sum = $result[$value[0]]['sum'] + $value[1];
$count = $result[$value[0]]['count'] + 1;
$result[$value[0]] = ['sum' => $sum , 'count' => $count, 'divided' => ($sum / $count)];
} else {
$result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
$myArray = [
["ALFA",213],
["ALFA",151],
["ALFA",197],
["BETA",167],
["ZETA",254],
["GAMA",138],
["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
//AVOID PESKY NOTICES FOR UNDEFINED INDEXES
if ( !array_key_exists($val[0],$a1) ) {
$a1[$val[0]] = array("count" => 0,"total" => 0);
$res[$val[0]] = 0;
}
//INCREMENT THE COUNT OF INSTANCES OF THIS KEY
$a1[$val[0]]["count"]++;
//INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
$a1[$val[0]]["total"]+=$val[1];
// UPDATE RESULT ARRAY
$res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}
print_r($res);
Should result in:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Sample: http://phpfiddle.org/lite/code/a7nt-5svf

PHP Counting inside an Array

I want to create a list where if its already in the array to add to the value +1.
Current Output
[1] => Array
(
[source] => 397
[value] => 1
)
[2] => Array
(
[source] => 397
[value] => 1
)
[3] => Array
(
[source] => 1314
[value] => 1
)
What I want to Achieve
[1] => Array
(
[source] => 397
[value] => 2
)
[2] => Array
(
[source] => 1314
[value] => 1
)
My current dulled down PHP
foreach ($submissions as $timefix) {
//Start countng
$data = array(
'source' => $timefix['parent']['id'],
'value' => '1'
);
$dataJson[] = $data;
}
print_r($dataJson);
Simply use an associated array:
$dataJson = array();
foreach ($submissions as $timefix) {
$id = $timefix['parent']['id'];
if (!isset($dataJson[$id])) {
$dataJson[$id] = array('source' => $id, 'value' => 1);
} else {
$dataJson[$id]['value']++;
}
}
$dataJson = array_values($dataJson); // reset the keys - you don't nessesarily need this
This is not exactly your desired output, as the array keys are not preserved, but if it suits you, you could use the item ID as the array key. This would simplify your code to the point of not needing to loop through the already available results:
foreach ($submissions as $timefix) {
$id = $timefix['parent']['id'];
if (array_key_exists($id, $dataJson)) {
$dataJson[$id]["value"]++;
} else {
$dataJson[$id] = [
"source" => $id,
"value" => 1
];
}
}
print_r($dataJson);
You should simplify this for yourself. Something like:
<?
$res = Array();
foreach ($original as $item) {
if (!isset($res[$item['source']])) $res[$item['source']] = $item['value'];
else $res[$item['source']] += $item['value'];
}
?>
After this, you will have array $res which will be something like:
Array(
[397] => 2,
[1314] => 1
)
Then, if you really need the format specified, you can use something like:
<?
$final = Array();
foreach ($res as $source=>$value) $final[] = Array(
'source' => $source,
'value' => $value
);
?>
This code will do the counting and produce a $new array as described in your example.
$data = array(
array('source' => 397, 'value' => 1),
array('source' => 397, 'value' => 1),
array('source' => 1314, 'value' => 1),
);
$new = array();
foreach ($data as $item)
{
$source = $item['source'];
if (isset($new[$source]))
$new[$source]['value'] += $item['value'];
else
$new[$source] = $item;
}
$new = array_values($new);
PHP has a function called array_count_values for that. May be you can use it
Example:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

Select arrays with multiple occurence from a array of arrys - PHP

My array is given below. Which contains more than one arrays.
Array
(
[0] => Array
(
[user_id] => 1
[name] => name1
)
[1] => Array
(
[user_id] => 2
[name] => name2
)
[2] => Array
(
[user_id] => 2
[name] => name2
)
[3] => Array
(
[user_id] => 3
[name] => name3
)
)<br/>
I need arrays which has more than one occurence.In this case
Array
(
[user_id] => 2
[name] => name2
)
Try this.
function get_multi_occur($my_array)
{
foreach ($my_array as $id => $a) {
$key = $a[user_id] . $a[name];
if ($s[$key]['cnt'] == 0) {
$s[$key]['cnt'] = 1;
$s[$key]['id'] = $id;
} else {
$s[$key]['cnt']++;
}
}
foreach ($s as $r) {
if ($r['cnt'] >= 2) {
$ret[] = $my_array[$r[id]];
}
}
return $ret;
}
foreach ($array as $key_1=>$sub_array_1)
{
foreach ($array as $key_2=>$sub_array_2)
{
if ($sub_array_1 == $sub_array_2 &&
$key_1 != $key_2)//prevent to compare same sub arrays
print_r($sub_array_1);
}
}
something like this
You can try
$array = Array(
"0" => Array("user_id" => 1,"name" => "name1"),
"1" => Array("user_id" => 2,"name" => "name2"),
"2" => Array("user_id" => 2,"name" => "name2"),
"3" => Array("user_id" => 3,"name" => "name3"));
$d = $s = array();
array_map(function ($v) use(&$d, &$s) {
array_key_exists($v['user_id'], $s) && ! array_key_exists($v['user_id'], $d) ? $d[$v['user_id']] = $v : $s[$v['user_id']] = $v;
}, $array);
var_dump($d);
Output
array
2 =>
array
'user_id' => int 2
'name' => string 'name2' (length=5)
Create a new array that will store data that have same values.
Try this code :
$array_existing = array();
$ctr = 0;
foreach ($first_array as $key => $first) :
foreach ($second_array as $keytwo => $second) :
if ($first['user_id'] == $second['user_id'] && $first['name'] == $second['name']) {
$array_existing[$ctr]['user_id'] = $first['user_id'];
$array_existing[$ctr]['name'] = $first['name'];
$array_existing[$ctr]['first_index'] = $key;
$array_existing[$ctr]['second_index'] = $keytwo;
$ctr++;
}
endforeach;
endforeach;
var_dump($array_existing);

Categories