Need to explode and string and make it as key value pairs - php

i have this data
[0] => 1#*#1-1
my requirement is explode from #*# and have to make generated array elements as key value pairs
Example
$data = explode("#*#",'1#*#1-1');
$data[0] =1;
$data[1] = 1-1;
now my requirement is make a dynamic associative array
array($data[1] => $data[0])

<?
$str = '1#*#1-1
3#*#1-2
5#*#1-3
7#*#1-4
9#*#1-5
11#*#1-6
13#*#1-7
15#*#1-8
17#*#1-9
19#*#1-10
2#*#2-1
4#*#2-2
6#*#2-3
8#*#2-4
10#*#2-5
12#*#2-6
14#*#2-7
16#*#2-8
18#*#2-9';
$ex = array_map('trim',explode("\n",$str));
$out = array();
foreach($ex as $e){
$ex2 = explode('#*#',$e);
$out[$ex2[1]] = $ex2[0];
}
print_r($out);
Array
(
[1-1] => 1
[1-2] => 3
[1-3] => 5
[1-4] => 7
[1-5] => 9
[1-6] => 11
[1-7] => 13
[1-8] => 15
[1-9] => 17
[1-10] => 19
[2-1] => 2
[2-2] => 4
[2-3] => 6
[2-4] => 8
[2-5] => 10
[2-6] => 12
[2-7] => 14
[2-8] => 16
[2-9] => 18
)
?>

<?php
$mydata = array();
$data = array('1#*#1-1');
list($key, $val) = explode('#*#', $data[0]);
$mydata[$val] = $key;
// Check work.
echo '<pre>' . print_r($mydata, TRUE) . '</pre>';

Related

Merge 2 element of same array into one in php

I have an array
Array
(
[0] => Array
(
[hrg_lid] => 214291464161204318
[pecon] => 0
[col2pe] => Karam
[col4pe] => 1
[col6pe] => 2
[col8pe] => 264
[col9pe] => 42
[col10pe] => 85
[col11pe] => 2
)
[1] => Array
(
[hrg_lid] => 707581464079555092
[pecon] => 1
[col2pe] => Dummy
[col4pe] =>
[col6pe] =>
[col8pe] => 12
[col9pe] => 0
[col10pe] => 0
[col11pe] => 2
[col12pe] => 1
[col13pe] => 1
)
[2] => Array
(
[hrg_lid] => 707581464079555092
[col5risk] => 2
[col6risk] => 2
[col7risk] => 1
[col8risk] => 2
[col9risk] => 1
[col10risk] => 1
[col11risk] => 2
)
I want to merge those elements which has same hrg_lid.
Expected Output
Array
(
[0] => Array
(
[hrg_lid] => 214291464161204318
[pecon] => 0
[col2pe] => Karam
[col4pe] => 1
[col6pe] => 2
[col8pe] => 264
[col9pe] => 42
[col10pe] => 85
[col11pe] => 2
)
[1] => Array
(
[hrg_lid] => 707581464079555092
[pecon] => 1
[col2pe] => Dummy
[col4pe] =>
[col6pe] =>
[col8pe] => 12
[col9pe] => 0
[col10pe] => 0
[col11pe] => 2
[col12pe] => 1
[col13pe] => 1
[col5risk] => 2
[col6risk] => 2
[col7risk] => 1
[col8risk] => 2
[col9risk] => 1
[col10risk] => 1
[col11risk] => 2
)
I tried following code
foreach($arr as $key => $value) {
$finalArray[$value['hrg_lid']] = $value;
}
but fails
I would use hrg_lid as array key - otherwise you have to check every element already in the output array for matches every time you add a new element:
$finalArray = array();
foreach($arr as $value) {
$hrg_lid = $value['hrg_lid'];
if (isset($finalArray[$hrg_lid])) {
// merge if element with this $hrg_lid is already present
$finalArray[$hrg_lid] = array_merge($finalArray[$hrg_lid], $value);
} else {
// save as new
$finalArray[$hrg_lid] = $value;
}
}
If you want to get normalized array keys, you can reset them afterwards:
$finalArray = array_values($finalArray);
The hrg_lid value must be the key of the array, if you won't change the keys, Try this :
for($i=0; $i < count($arr);$i++)
{
for($j=0; $j < count($finalArray);$j++)
{
if($arr[$i]['hrg_lid'] == $finalArray[$j]['hrg_lid'])
{
$finalArray[$j] = array_merge($finalArray[$j],$arr[$i]);
break;
}
}
}
Try soomething like :
$finalArray = [];
foreach($arr as $singleArray) {
$id = $singleArray['hrg_lid'];
if (isset($finalArray[$id])) {
$finalArray = array_merge($finalArray[$id], $singleArray);
} else {
$finalArray[] = $singleArray;
}
}
You could try something like that :
$tmpArray = array();
$finalArray = array();
// We merge the arrays which have the same value in 'hrg_lid' col
foreach($source as $array){
$key = $array['hrg_lid'];
array_shift($array);
if(array_key_exists($key, $tmpArray)){
$tmpArray[$key] = array_merge($tmpArray[$key], $array);
}else{
$tmpArray[$key] = $array;
}
}
// We build the final array
foreach($tmpArray as $key => $value){
$finalArray[] = array_merge(array('hrg_lid' => $key), $value);
}

How to convert array into json

I have this type of Array
Array
(
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
);
I need to convert this array into following type of json
data: [
['Samy Jeremiah',55 ],
['Nelson Owen',93 ],
['McMaster Ashlie',88 ] ,
['Marsh Harlow',97 ] ,
['Macfarquhar Aiden',95 ],
['Lowe Sophie',91 ]
]
Try this
<?php
$yourArray = array(
'0' => 'Samy Jeremiah,55',
'1' => 'Nelson Owen,93',
'2' => 'McMaster Ashlie,88',
'3' => 'Marsh Harlow,97',
'4' => 'Macfarquhar Aiden,95',
'5' => 'Lowe Sophie,91',
);
#Check output 01
//print_r($yourArray);
foreach ($yourArray as $value) {
$explodeValue = explode( ',', $value );
$newName []= array($explodeValue[0] => $explodeValue[1]);
}
#Check output 02
//print_r($newName);
#Check output 03
echo(json_encode($newName));
?>
PHPFiddle Preview
Output 01
Array (
[0] => Samy Jeremiah,55
[1] => Nelson Owen,93
[2] => McMaster Ashlie,88
[3] => Marsh Harlow,97
[4] => Macfarquhar Aiden,95
[5] => Lowe Sophie,91
)
Output 02
Array (
[0] => Array ( [Samy Jeremiah] => 55 )
[1] => Array ( [Nelson Owen] => 93 )
[2] => Array ( [McMaster Ashlie] => 88 )
[3] => Array ( [Marsh Harlow] => 97 )
[4] => Array ( [Macfarquhar Aiden] => 95 )
[5] => Array ( [Lowe Sophie] => 91 )
)
Output 03
[
{"Samy Jeremiah":"55"},
{"Nelson Owen":"93"},
{"McMaster Ashlie":"88"},
{"Marsh Harlow":"97"},
{"Macfarquhar Aiden":"95"},
{"Lowe Sophie":"91"}
]
Your desired result is an array of arrays. You have to split each entry of your array into 2 entities and push them as an array into a new array, then json_encode() the new array.
This php-snippet only works, if your input is consistantly an array of strings, containing each one comma as separator between name and int-value:
$arr2 = array();
foreach($arr1 as $e) {
list($name, $val) = explode(',', $e);
$arr2[] = array($name, (int)$val);
}
echo json_encode($arr2);
Use below code
$data = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$res = array();
foreach($data as $e) {
$list = explode(',', $e);
$res[] = array($list[0], $list[1]);
}
echo json_encode(['data'=>$arr2]);
Output
{"data":[
["Samy Jeremiah",55],
["Nelson Owen",93],
["McMaster Ashlie",88],
["Marsh Harlow",97],
["Macfarquhar Aiden",95],
["Lowe Sophie",91]
]
}
Using the json_encode you can achieve what you want.
Suppose your array name is $arr, so now apply the json_encode.
echo json_encode(array('data'=>$arr)); //your json will be print here
Real time Example:
$arr = array('Samy Jeremiah,55', 'Nelson Owen,93', 'McMaster Ashlie,88', 'Marsh Harlow,97', 'Macfarquhar Aiden,95', 'Lowe Sophie,91');
$new_arr = array();
foreach($arr as $k => $val){
$na = explode(",", $val);
$na[0] = "'".$na[0]."'";
$value = implode(",", $na);
$new_arr[$k] = $value;
}
echo json_encode(array("data" => $new_arr));

Implode multidimensional array with different glue in php

I have array like below:
Array
(
[22] => Array
(
[0] => 60
[29] => Array
(
[0] => 6
)
[30] => Array
(
[0] => 5
[1] => 8
)
[31] => Array
(
[0] => 7
[1] => 9
[2] => 14
[3] => 26
)
)
[23] => 12
[35] =>10
[42] =>22
)
now i want to implode array like
60[6][5||8][7||9||14||26]|12|10|22
I have tried below code:
$arr = array_map(function($el){ return $el['tag_id']; }, $arr);
$str = implode(',', $arr);
But it is not implode with required glue
How can i do it?
you can use this code
<?php
$a= Array(
22 => Array(
0 => 60,
29 => Array(
0 => 6
),
30 => Array
(
0 => 5,
1 => 8
),
31 => Array
(
0 => 7,
1 => 9,
2 => 14,
3 => 26
),
),
23 => 12,
35 =>10,
42 =>22,
);
$string='';
foreach($a as $arr){
if(is_array($arr)){
foreach($arr as $array){
if(is_array($array)){
$string .= '['.implode("||",$array).']';
}else{
if($string!==''){ $string .= '|';}
$string .= $array;
}
}
}else{
if($string!==''){ $string .= '|';}
$string .= $arr;
}
}
echo $string;die;
?>
Out put wil be
60[6][5||8][7||9||14||26]|12|10|22
Desired result without foreach.
$array = [
22 => [
0 => 60,
29 => [
0 => 6
],
30 => [
0 => 5,
1 => 8
],
31 => [
0 => 7,
1 => 9,
2 => 14,
3 => 26
]
],
23 => 12,
35 => 10,
42 => 22
];
$result = implode('|', array_map(function($item)
{
return is_array($item) // convert sub array into string
? implode('', array_map(function($inner_item)
{
return is_array($inner_item) // convert inner array into string
? '[' . implode('||', $inner_item) . ']'
: $inner_item;
}, $item))
: $item;
}, $array));
var_dump($result);
So, we have 3 types of delimiters: '|' - first level, ''(empty) - second level, '||' - third level.
You can use foreach and implode to achieve your pattern:
<?php
header('Content-Type: text/plain');
$arr = array();
$arr22 = array();
$arr22[0] = 60;
$arr22[29] = array(6);
$arr22[30] = array(5,8);
$arr22[31] = array(7,9,14,26);
$arr[22] = $arr22;
$arr[23] = 12;
$arr[35] = 10;
$arr[42] = 22;
$output = '';
foreach($arr as $entry) {
if(!is_array($entry)) {
$output .= $entry;
} else {
// array
foreach($entry as $inner) {
if(is_array($inner)) {
$output .= '[' . implode('||', $inner) . ']';
} else {
$output .= $inner;
}
}
}
$output .= '|';
}
echo substr($output, 0, strlen($output) - 1);
?>
which outputs:
60[6][5||8][7||9||14||26]|12|10|22
This should work for you:
Here the glue is configurable as you desired and this logic is built on the recursive call hence this will work for any level of multidimensional array:
<?php
$arrVal = array (
'22' => array(
'0' => 60,
'29' => array(
'0' => 6
),
'30' => array (
'0' => 5,
'1' => 8
),
'31' => array (
'0' => 7,
'1' => 9,
'2' => 14,
'3' => 26
)
),
'23' => 12,
'35' => 10,
'42' => 22
);
//60[6][5||8][7||9||14||26]|12|10|22
$constructedValue = "";
$glue = "||";
echo $constructedValue = implodeMultiArr($arrVal,$glue);
function implodeMultiArr($arrVal,$glue) {
$i = 0;
$constructedValue = "";
foreach ( $arrVal as $k=>$v) {
if ( is_array($v) ) {
$constructedValue .= !empty($constructedValue) ? "[".implodeMultiArr($v,$glue)."]" : implodeMultiArr($v,$glue)."]" ;
} else {
$constructedValue .= !empty($constructedValue) ? $glue.$v : $v ;
}
$i++;
}
return $constructedValue;
}

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 group values from array

I have this array:
Array (
[061716v] => 1
[061610A] => 1
[062433AP] => 1
[063868M] => 2
[059173V] => 3
[061579A] => 3
[062404AP] => 3
[059179V] => 4
[061582A] => 4
[061697V] => 4
[062407AP] => 4
)
How can i get this:
Array (
[1] => 061716v,061610A,062433AP
[2] => 063868M
[3] => 059173V,061579A,062404AP
[4] => 059179V,061582A,061697V,062407AP
)
In PHP single foreach() will do the job:-
$final_array = [];
foreach($initial_array as $key=>$val){
$final_array[$val] = isset($final_array[$val]) ? $final_array[$val].','.$key : $key;
}
print_r($final_array);
Output:-https://3v4l.org/lSKE2
// You also can use implode to skip isset checks
$group = [];
foreach ($initialArray as $key => $value) {
$group[$value][] = $key;
}
$result = array_map(function($v) { return implode(",",$v); }, $group);
print_r($result);

Categories