creating a array with index value dynamically in php - php

hi i want to create an array dynamically with the index value and the key value.
here $head is the array name and $values is the key value
$head = Array ( [0] => Dis_id [1] => Dis_Desc [2] => Dis_Per [3] => Dis_val )
$values = Array ([0] => Dl-Dis1 [1] => Discount [2] => 7.500 [3] => 26.25 )
Array ([0] => Dl-Dis2 [1] => Discount [2] => 2.500 [3] => 73.13 )
foreach($values as $valu => $key)
{
$value = $value + array($head[$valu]=>$key.",");
}
echo '<pre>';
print_r($value);
The output will be as
Array
(
[Dis_id] => Dl-Dis2,
[Dis_Desc] => Discount,
[Dis_Per] => 2.500,
[Dis_val] => 73.13,
)
But the output i need is as follows
Array
(
[Dis_id] => Dl-Dis1,
[Dis_Desc] => Discount,
[Dis_Per] => 7.500,
[Dis_val] => 26.25,
)
Array
(
[Dis_id] => Dl-Dis2,
[Dis_Desc] => Discount,
[Dis_Per] => 2.500,
[Dis_val] => 73.13,
)
i dont know how to do please help me
update to get my output
$values = array(array (0 => 'Dl-Dis1', 1 => 'Discount', 2 => 7.500, 3 => 26.25 ), array (0 => 'Dl-Dis2', 1 => 'Discount', 2 => 2.500, 3 => 73.13 )) ;
thank u all

You may need to use array_combine. While under the loop, combine the $head and the values itself to it and put it inside a new container. Consider this example:
$head = Array ( 0 => 'Dis_id', 1 => 'Dis_Desc', 2 => 'Dis_Per', 3 => 'Dis_val', );
$values = array(array (0 => 'Dl-Dis1', 1 => 'Discount', 2 => 7.500, 3 => 26.25 ), array (0 => 'Dl-Dis2', 1 => 'Discount', 2 => 2.500, 3 => 73.13 )) ;
$new_values = array();
foreach($values as $value) {
$new_values[] = array_combine($head, $value);
}
Sample Output

You can do it like this:
$head = array ( 0 => 'Dis_id', 1 => 'Dis_Desc', 2 => 'Dis_Per', 3 => 'Dis_val' );
$values = array(array (0 => 'Dl-Dis1', 1 => 'Discount', 2 => '7.500', 3 => 26.25 ),
array (0 => 'Dl-Dis2', 1 => 'Discount', 2 => 2.500, 3 => 73.13 ));
$result = array();
foreach($values as $value) {
$res = array();
foreach ($value as $key => $val) {
$res[$head[$key]] = $val;
}
$result[] = $res;
}
echo '<pre>';
print_r($result);

Related

Get sum of values which have same value for key php array

I have below array,
Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )
What i want to send to have JSON with below format
It will get some of Equal category name and then send it as json.
[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]
How can i achieve this?
Was thinking to get foreach loop and then make compare of category_name and use .=+ to get sum? but i lost there,
Thanks,
Try below solution:
<?php
$array = array (
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);
$new_array = array();
foreach($array as $a){
if(!isset($new_array[$a['category_name']]['amount'])){
$new_array[$a['category_name']]['amount'] = 0;
}
$new_array[$a['category_name']] = array(
'category_name' => $a['category_name'],
'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
);
}
//print_r(array_values($new_array));
echo json_encode(array_values($new_array));
Output
[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]
Possible solution:
$categoriesArray = array();
foreach ($yourArray as $arrayItem) {
if (!isset($categoriesArray[$arrayItem['category_name']])) {
$categoriesArray[$arrayItem['category_name']] = array(
'category_name' => $arrayItem['category_name'],
'sum' => 0
);
}
$categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}
$categoriesArray = json_encode(array_values($categoriesArray));
Assuming $input is your array and $output is the JSON string:
$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
$categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
$categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

unique array on base on value of specific key

I have the following array:
Array
(
[0] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 2
)
[1] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 3
)
[2] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 4
)
[3] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 23
)
[4] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 24
)
)
I have two different hotelID keys. I would like to extract only one element (the first one) where the hotelID is unique in whole array. I am trying with following code:
$data['uniqueHotels'] = array_map('unserialize', array_unique(array_map('serialize', $hotels)));
but without any luck so far.
Anyone can give me a hint?
If looking for the first element:
<?php
$hotels = array(
array(
'id' => 1,
'hotelID' => 10
),
array(
'id' => 2,
'hotelID' => 10,
),
array(
'id' => 3,
'hotelID' => 20,
),
array(
'id' => 4,
'hotelID' => 20,
),
);
function getUniqueHotels($hotels) {
$uniqueHotels = array();
foreach($hotels as $hotel) {
$niddle = $hotel['hotelID'];
if(array_key_exists($niddle, $uniqueHotels)) continue;
$uniqueHotels[$niddle] = $hotel;
}
return $uniqueHotels;
}
$unique_hotels = getUniqueHotels($hotels);
print_r($unique_hotels);
results in:
Array
(
[10] => Array
(
[id] => 1
[hotelID] => 10
)
[20] => Array
(
[id] => 3
[hotelID] => 20
)
)
You could simply loop through the array and add them to a new array, indexed by hotelID. This way any duplicates will just overwrite the existing value and you end up with one entry per hotel:
$unique = array();
foreach ($hotels as $value)
{
$unique[$value['hotelID']] = $value;
}
$data['uniqueHotels'] = array_values($unique);
Here is a dynmaic solution:
function uniqueAssocArray($array, $uniqueKey){
$unique = array();
foreach ($array as $value){
$unique[$value[$uniqueKey]] = $value;
}
$data = array_values($unique);
return $data;
}
How to use:
uniqueAssocArray($yourArray, 'theKey');
along the lines of what you're trying,
array_unique(array_map(function($hotel) { return $hotel['hotelID']; }, $array))

count the times a certain key name shows up in a multi-array?

How may I count the times a key shows up in a multi-array?
In the below example, weight should return 2, and reps 4. Does PHP have a built-in function for this?
[0] => Array
(
[0] => Array
(
[weight] => 317.51474856007
[reps] => 10
)
[1] => Array
(
[weight] => 50
[reps] => 10
)
[2] => Array
(
[reps] => 10
)
[3] => Array
(
[reps] => 10
)
)
you can try something like this:
function counter($array){
$result = array();
foreach($array as $key=>$value){
foreach($value as $name => $val){
$result[$name][]=$val;
}
}
return array('all'=>$result,'count weight'=>count($result['weight']),'count reps'=>count($result['reps']));
}
$array= Array(
'0' => Array
(
'weight' => 317.51474856007,
'reps' => 10
),
'1' => Array
(
'weight' => 50,
'reps' => 10
),
'2' => Array
(
'reps' => 12
),
'3' => Array
(
'reps' => 10
)
);
$resp = counter($array);
var_dump($resp);
Try this one liner using array_walk_recursive():
Given your array, $arr
array_walk_recursive($arr, function($v, $k)use(&$count){if(array_key_exists($k, $count))$count[$k]++;else $count[$k]=1;},$count=array());
print_r($count);
See demo
or the old fashioned way:
$count = array();
foreach ($arr as $ar){
foreach ($ar as $k=>$v){
if (array_key_exists($k, $count)){
$count[$k]++;
}
else{
$count[$k] = 1;
}
}
}
print_r($count);
See demo
Output:
Array
(
[weight] => 2
[reps] => 4
)
you can try this:
$array= Array(
'0' => Array
(
'weight' => 317.51474856007,
'reps' => 10
),
'1' => Array
(
'weight' => 50,
'reps' => 10
),
'2' => Array
(
'reps' => 10
),
'3' => Array
(
'reps' => 10
)
);
$weight=0;
$reps=0;
//print_r($array);
foreach($array as $key=>$val){
if(isset($val['weight'])){
echo $val['weight']."<br>";
$weight++;
}
if(isset($val['reps'])){
echo $val['reps']."<br>";
$resp++;
}
}
echo $weight." ".$resp;

Removing items from an array based on items in another array

I have 2 arrays:
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 10 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 17:32:26 ) [1] => Array ( [intTrackId] => 1 [intAverageRating] => 7 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 18:54:35 ))
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 5.5000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ) [1] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
I want to remove the items in the second which have a matching track ID in the first. So in this example, I would get:
Array ( [0] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
Is this possible with array_filter or is this a little complex for that?
Just use array_udiff() - it's intended to do this:
$one = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 10, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 17:32:26' ),
1 => Array ('intTrackId' => 1, 'intAverageRating' => 7, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 18:54:35' )
);
$two = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 5.5000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' ),
1 => Array ('intTrackId' => 361, 'intAverageRating' => 8.0000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' )
);
$result = array_udiff($two, $one, function($x, $y)
{
return $x['intTrackId']-$y['intTrackId'];
});
Yes it can be done with array_filter:
$array1 = array(...);
$array2 = array(...);
$newArray = array_filter($array2, function($item) use ($array1){
foreach($array1 as $elem){
if($item['intTrackId'] == $elem['intTrackId']){
return false;
}
}
return true;
});
I would first create a loop and store all track IDs from the first array in a separate array.
Then I'd loop over the second array and delete those keys that exist in the track ID array.
$track_ids = array();
foreach($array1 as $index => $items) {
$track_ids[$items['intTrackId']] = $index;
}
foreach($array2 as $items) {
if (isset($track_ids[$items['intTrackId']])) {
unset($array2[$track_ids[$items['intTrackId']]]);
}
}

Merge arrays (PHP)

How combine arrays in this way?
source:
Array
(
[0] => Array
(
[id] => 3
[title] => book
[tval] => 10000
)
[1] => Array
(
[id] => 3
[title] => book
[tval] => 1700
)
[3] => Array
(
[id] => 27
[title] => fruit
[tval] => 3000
)
.......
)
result:
Array
(
[0] => Array
(
[id] => 3
[title] => book
[tval] => 10000,1700
)
[1] => Array
(
[id] => 27
[title] => fruit
[tval] => 3000
)
.......
)
please help to solve this problem,
thanks!!!
sorry for bad english(
This should work:
$result = array();
foreach($array as $elem) {
$key = $elem['id'];
if (isset($result[$key])) {
$result[$key]['tval'] .= ',' . $elem['tval'];
} else {
$result[$key] = $elem;
}
}
This basically groups elements by id, concatenating tvals (separated by ,).
Simply building slightly on user576875's method:
$a = array ( 0 => array ( 'id' => 3,
'title' => 'book',
'tval' => 10000
),
1 => array ( 'id' => 3,
'title' => 'book',
'tval' => 1700
),
3 => array ( 'id' => 27,
'bcalias' => 'fruit',
'tval' => 3000
)
);
$result = array();
foreach ($a as $elem) {
$key = $elem['id'];
if (isset($result[$key])) {
$result[$key]['tval'] .= ',' . $elem['tval'];
} else {
$result[$key] = $elem;
}
}
$result = array_merge($result);
var_dump($result);
gives a result of:
array
0 =>
array
'id' => int 3
'title' => string 'book' (length=4)
'tval' => string '10000,1700' (length=10)
1 =>
array
'id' => int 27
'bcalias' => string 'fruit' (length=5)
'tval' => int 3000
The only real difference is the array_merge() to reset the keys

Categories