How can I merge these array together?
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.700000
[count] => 300
[text] => Chris
)
)
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.900000
[count] => 400
[text] => Chris
)
[1] => Array
(
[type] => Person
[relevance] => 0.500000
[count] => 200
[text] => Tom
)
)
or array like this:
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.700000
[count] => 300
[text] => Chris
)
[1] => Array
(
[type] => Person
[relevance] => 0.900000
[count] => 400
[text] => Chris
)
[2] => Array
(
[type] => Person
[relevance] => 0.500000
[count] => 200
[text] => Tom
)
)
The expected result is:
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.800000
[count] => 700
[text] => Chris
)
[1] => Array
(
[type] => Person
[relevance] => 0.500000
[count] => 200
[text] => Tom
)
)
[relevance] value is an average number
[count] value is an incremental number
The merging of these array should base on [text] value.
How can I do this with php in a fast way?
Thanks for helping.
If this is the array
$array = Array(
Array(
'type' => 'Person',
'relevance' => .7,
'count' => 300,
'text' => 'Chris'
),
Array(
'type' => 'Person',
'relevance' => .9,
'count' => 400,
'text' => 'Chris'
),
Array(
'type' => 'Person',
'relevance' => .5,
'count' => 200,
'text' => 'Tom'
),
);
then:
$tmp = Array();
foreach($array as $obj) {
if(!isset($tmp[$obj['text']])) {
$tmp[$obj['text']] = array_merge(Array('total_count'=>1),$obj);
continue;
}
$tmp[$obj['text']]['count'] += $obj['count'];
$tmp[$obj['text']]['relevance'] += $obj['relevance'];
$tmp[$obj['text']]['total_count']++; // useful for average calculation
}
$result = Array();
foreach($tmp as $key=>$obj) {
$obj['relevance'] = $obj['relevance']/$obj['total_count'];
unset($obj['total_count']); // useless now
$result[] = $obj;
}
print_r($result);
Something like this maybe:
$newArray = array();
foreach ($oldArray as $item) {
if (!array_key_exists($item['text'], $newArray)) {
$newArray[$item['text']] = $item;
$newArray[$item['relevance_values']] = array();
} else {
$newArray[$item['text']]['count'] += $item['count'];
$newArray[$item['relevance_values']][] = $item['relevance'];
}
}
foreach ($newArray as $item) {
$relevance = 0;
foreach ($item['relevance_values'] as $value) {
$relevance += $value;
}
$item['relevance'] = $relevance / count($item['relevance_values']);
}
Try this:
function mergeOnText($array){
$results = array();
foreach($array as $person){
$found = -1;
foreach($results as $i => $res)
if($res['text'] == $person['text']){
$found = $i;
break;
}
if($found > -1){
$results[$found]['relevance'][] = $person['relevance'];
$results[$found]['count'] += $person['count'];
} else {
$results[] = $person;
}
}
foreach($results as $i => $res)
$results[$i]['relevance'] = array_sum($res['relevance']) / count($res['relevance']);
return $results;
}
Related
I have an array something like below. I want to merge the nested array and display the totals. Here ID = 60.I want to merge this [0] and [1] depending in the ID value i.e., 60.
Array(
[0] => Array
(
[ID] => 60
[TOTAL] => 500
)
[1] => Array
(
[ID] => 60
[TOTAL] => 600
)
[2] => Array
(
[ID] => 61
[TOTAL] => 600
)
)
I tried with two for loops
foreach($result as $key=>$value){
foreach($result as $key1 => $value1){
// Do stuffs here
}
}
I want the output as
Array(
[0] => Array(
[ID] =>60
[TOTAL] => 1100
)
[1] =>Array(
[ID] =>61
[TOTAL] => 600
)
)
<?php
$result = Array(
Array
(
'ID' => 60,
'TOTAL' => 500
),
Array
(
'ID' => 60,
'TOTAL' => 600
),
Array
(
'ID' => 61,
'TOTAL' => 600
)
);
$set = [];
foreach($result as $data){
if(!isset($set[$data['ID']])) $set[$data['ID']] = 0;
$set[$data['ID']] += $data['TOTAL'];
}
$result_set = [];
foreach($set as $id => $total){
$result_set[] = [
'ID' => $id,
'TOTAL' => $total
];
}
print_r($result_set);
Demo: https://3v4l.org/NMmHC
We store IDs as keys in our $set array and keep adding the total to it whenever we come across the same key in the foreach loop.
In the end, we collect the results in a new array with ID and it's respective total.
My suggestion is to use array_reduce() which iteratively reduce the array to a single value using a callback function.
$arr = [['ID' => 60,'TOTAL' => 500],['ID' => 60,'TOTAL' => 600],['ID' => 61,'TOTAL' => 600]];
$arr = array_reduce($arr, function($acc, $new) {
if (!isset($acc[$new['ID']])) {
$acc[$new['ID']] = $new;
return $acc;
}
$acc[$new['ID']]['TOTAL'] += $new['TOTAL'];
return $acc;
}, []);
echo '<pre>', print_r(array_values($arr));
Working demo.
Solution 1
$arrayvariable=Array(
[0] => Array
(
[ID] => 60
[TOTAL] => 500
)
[1] => Array
(
[ID] => 60
[TOTAL] => 600
)
[2] => Array
(
[ID] => 61
[TOTAL] => 600
)
)
$output = array_reduce($arrayvariable, function (array $compare, array $item) {
$intrestkey = $item ['ID'];
if (array_key_exists($intrestkey, $compare)) {
$compare [$intrestkey] ['TOTAL'] += $item ['TOTAL'];
} else {
$compare [$intrestkey] = $item;
}
return $compare;
}, array());
$incremetedmerged_array = array_values($output);
print_r($incremetedmerged_array); //Produces
Array(
[0] => Array(
[ID] =>60
[TOTAL] => 1100
)
[1] =>Array(
[ID] =>61
[TOTAL] => 600
)
)
i'm deploying a shipping service to shopify using a webhook to get this data converted in json, i trying to send only the fields name, quantity, sku and id in a table.
i'm using foreach function to make it but no results.
Grettings!
[fulfillments] => Array
(
[0] => stdClass Object
(
[line_items] => Array
(
[0] => stdClass Object
(
[fulfillment_service] => manual
[fulfillment_status] => fulfilled
[gift_card] =>
[grams] => 2000
[id] => 470651995
[price] => 200.00
[product_id] => 304163215
[quantity] => 1
[requires_shipping] => 1
[sku] => 123456789
[taxable] =>
[title] => Product 1
[variant_id] => 709836495
[variant_title] =>
[vendor] => kkk
[name] => Product 1
)
[1] => stdClass Object
(
[fulfillment_service] => manual
[fulfillment_status] => fulfilled
[gift_card] =>
[grams] => 2000
[id] => 470651995
[price] => 200.00
[product_id] => 304163215
[quantity] => 3
[requires_shipping] => 1
[sku] => 123456789
[taxable] =>
[title] => Product 2
[variant_id] => 709836495
[variant_title] =>
[vendor] => kkk
[name] => Product 2
)
)
)
)
$your_array = json_decode(json_encode($your_array), true);
//it will casts from StdClass to an array
$your_array = $your_array['fulfillments'];
$result_array = array();
$yaCnt = count($your_array);
for($i = 0; $i < $yaCnt; ++$i)
{
$items = $yaCnt[$i]['line_items'];
$iCnt = count($items);
for($j = 0; $j < $iCnt; ++$j)
{
$result_array[] = array(
'name' => $items[$j]['name'],
'quantity' => $items[$j]['quantity'],
'sku' => $items[$j]['sku'],
'id' => $items[$j]['id']
);
}
}
print_r($result_array);
Try the following foreach(), I have assumed you store all the initial data in the variable $fulfillments
$items = array();
foreach($fulfillments[0]->line_items as $item)
{
$items[] = array(
"name" => $item->name,
"quantity" => $item->quantity,
"sku" => $item->sku,
"id" => $item->id
);
}
echo json_encode($items);
<?php
$yourData = array();
$shippingData =array();
foreach ($yourData as $fulfillments) {
foreach ($fulfillments->line_items as $line_items) {
$shippingData[] = array(
'name' => $line_items->name,
'quantity' => $line_items->quantity,
'sku' => $line_items->sku,
'id' => $line_items->id
);
}
}
echo json_encode($shippingData);
I have following array :
[1] => Array
(
[entity_id] => 5877
[parent_id] => 5862
[label] => Railbikes
[name] => railbikes
[icon] => books.svg
[level] => 5
[tab_id] => 353
)
[2] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 354
)
[3] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 357
)
In this array label => Tournaments repeats twice and this is the case for whole array many labels are repeating twice , thrice and many time .
I want this array to be shown like that there will be a unique label and there is tab_id in each array which is different . This tab_id sholdd be appended to the unique label .
The final array should look like this .
[1] => Array
(
[entity_id] => 5877
[parent_id] => 5862
[label] => Railbikes
[name] => railbikes
[icon] => books.svg
[level] => 5
[tab_id] => 353
)
[2] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 354 , 357
)
Thanks.
$arr = array(1 => array
(
entity_id => 5877,
parent_id => 5862,
label => Railbikes,
name => railbikes,
icon => books.svg,
level => 5,
tab_id => 353
),
2 => array
(
entity_id => 5756,
parent_id => 5754,
label => Tournaments,
name => tournaments,
icon => books.svg,
level => 5,
tab_id => 354
),
3 => array
(
entity_id => 5756,
parent_id => 5754,
label => Tournaments,
name => tournaments,
icon => books.svg,
level => 5,
tab_id => 357
)
);
print("<pre>");
foreach ($arr AS $key => $value){
/*foreach ($value AS $innerKey => $innerValue){
}*/
if($arr[$key]['label'] == $arr[$key-1]['label'] )
{
$newArr[$key-1]['tab_id'] = $arr[$key]['tab_id'].",". $arr[$key-1]['tab_id'];
}
else{
$newArr[$key]= $arr[$key];
}
}
print_r($newArr);
Try this out
$new_array = array();
$items = array();
foreach( $array as $item )
{
$check = array_search( $item['entity_id'], $items, true );
if ( $check === false )
{
$temp = $item;
$temp['tab_id'] = array( $item['tab_id'] );
$new_array[] = $temp;
$items[] = $temp['entity_id'];
}
else
{
$new_array[$check]['tab_id'][] = $item['tab_id'];
}
}
where $array is your original array the you showed us. You can replace it at the end with $array = $new_array; if you want to keep the same name in the rest of the code.
Also, keep in mind that tab_id is now an array to fit with your requirement.
If you really want to keep it as in your example, you could use
$new_array = array();
$items = array();
foreach( $array as $item )
{
$check = array_search( $item['entity_id'], $items, true );
if ( $check === false )
{
$new_array[] = $item;
$items[] = $item['entity_id'];
}
else
{
$new_array[$check]['tab_id'] .= ', '.$item['tab_id'];
}
}
If the entity_id is always the same then you can 'cheat' a bit:
$new_array = array();
foreach($array as $item)
{
if(!isset($new_array[$item['entity_id']]) $new_array[$item['entity_id']] = $item;
}
$new_array = array_values($new_array);
PS: Always try to prevent double data, doesn't make your script faster ;)
I have the array about:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[product] => Array
(
[0] => t-shirt
[1] => earing
[2] => clock
)
[price] => Array
(
[0] => 100.00
[1] => 32.00
[2] => 898.00
)
)
I want to do this:
Array
(
[0] => Array
(
[0] => 1
[1] => t-shirt
[2] => 100.00
)
[1] => Array
(
[0] => 2
[1] => earing
[2] => 32.00
)
[2] => Array
(
[0] => 3
[1] => clock
[2] => 898.00
)
)
You can try with:
$input = array( /* your input array */ );
$output = array();
foreach ($input as $data) {
for ($i = 0; $i < count($data); $i++) {
if (!isset($output[$i])) {
$output[$i] = array();
}
$output[$i][] = $data[$i];
}
}
Well or like this.
$test = array(
'id' => array(
1,2,3
),
'product' => array(
'tshirt', 'ewew', 'shorts'
),
'price' => array(
'10.00', '20.00', '30.00'
)
);
$newarray = array();
foreach($test['id'] as $k => $v){
$newarray[$k] = array(
$v, $test['product'][$k], $test['price'][$k]
);
}
echo '<pre>';
print_r($newarray);
Example live
how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);