php turning array into multi-dimensional array - php

i have a (dynamic) array, which in this example contains 4 sets of data (5 fields per set), but it could be only one set or up to 25 sets.
Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
which i'd like to turn into something like
Array ( Array ( [lightwattage1] => 50 [lightvoltage1] => 12 [lightquantity1] => 2 [lightusage1] => 4 [lightcomment1] => ),
Array ( [lightwattage2] => 60 [lightvoltage2] => 24 [lightquantity2] => 4 [lightusage2] => 5 [lightcomment2] => ),
Array ( [lightwattage3] => 30 [lightvoltage3] => 240 [lightquantity3] => 4 [lightusage3] => 2 [lightcomment3] => ),
Array ( [lightwattage4] => 25 [lightvoltage4] => 12 [lightquantity4] => 2 [lightusage4] => 6 [lightcomment4] => )
)
the original array is created this way:
$light = Array();
foreach( $_POST as $key => $val )
{
//field names that start with light to go in this array
if (strpos($key, 'light') === 0) {
$light[$key] = $val;
}
}
the field name digit is already added with JS before form submission, and not by php script.
any hint much appreciated.

This is not an exacty answer to you question, but...
You can use arrays in POST variables like so:
<input name="light[1][wattage]" />
<input name="light[1][voltage]" />
<input name="light[2][wattage]" />
<input name="light[2][voltage]" />
will give you:
$_POST['light'] == array(
1 => array(
'wattage' => '...',
'voltage' => '...',
),
2 => array(
'wattage' => '...',
'voltage' => '...',
),
)

Try this:
$prefixes = array();
$postfixes = array();
foreach($original_array as $key=>$value)
{
preg_match('/^([^\d]*)(\d+)$/',$key,$matches);
if(count($matches)>1)
{
if(!in_array($matches[1], $prefixes)) $prefixes[] = $matches[1];
if(!in_array($matches[2], $postfixes)) $postfixes[] = $matches[2];
}
}
$new_array = array();
foreach($postfixes as $postfix)
{
$new_element = array();
foreach($prefixes as $prefix)
{
if(isset($original_array[$prefix.$postfix])) $new_element[$prefix.$postfix] = $original_array[$prefix.$postfix];
}
$new_array[] = $new_element;
}
given an $original_array equal to described, will produce $new_array:
Array
(
[0] => Array
(
[lightwattage1] => 50
[lightvoltage1] => 12
[lightquantity1] => 2
[lightusage1] => 4
[lightcomment1] =>
)
[1] => Array
(
[lightwattage2] => 60
[lightvoltage2] => 24
[lightquantity2] => 4
[lightusage2] => 5
[lightcomment2] =>
)
[2] => Array
(
[lightwattage3] => 30
[lightvoltage3] => 240
[lightquantity3] => 4
[lightusage3] => 2
[lightcomment3] =>
)
[3] => Array
(
[lightwattage4] => 25
[lightvoltage4] => 12
[lightquantity4] => 2
[lightusage4] => 6
[lightcomment4] =>
)
)
I was uncertain about how much you knew about the elements or their order, so this code basically takes any collection of elements that end in numbers and rearranges them in groups that have the same ending number.

Try this:
$outarr = array()
$subarr = array()
$i=0;
foreach($_POST as $key => $val)
{
//only include keys starting with light:
if (strpos("light", $key)==0)
{
//create a new subarray each time we find a key that starts with "lightwattage":
if ($i>0 && strpos("lightwattage", $key)==0)
{
$outarr[] = $subarr;
}
$subarr[$key] = $val;
$i++;
}
}
$outarr[] = $subarr;
//$outarr contains what you want here

Related

How to replace specific array string values with corresponding numbers in PHP?

I have an array with some repeating string values. How to replace these string values (as a whole, because some words are repeated in others strings) with corresponding specific numeric values, as bellow?
deloc = 1
foarte puţin = 2
mediu = 3
mult = 4
foarte mult = 5
This is the array (example):
array = (
"tensionat" => "mediu",
"trist" => "mult",
"melancolic" => "deloc",
"fara_speranta" => "foarte puțin",
"nefolositor"] => "deloc",
"ingrijorat" => "foarte mult",
"amarat" => "deloc",
"anxios" => "mediu"
);
How can this
Try this
$data = array (
"tensionat" => "mediu",
"trist" => "mult",
"melancolic" => "deloc",
"fara_speranta" => "foarte puțin",
"nefolositor" => "deloc",
"ingrijorat" => "foarte mult",
"amarat" => "deloc",
"anxios" => "mediu"
);
$repl = array (
'deloc' => 1,
'foarte puţin' => 2,
'mediu' => 3,
'mult' => 4,
'foarte mult' => 5,
);
$result = array ();
foreach ($data as $key => $value) {
$result[$key] = !empty($repl[$value]) ? $repl[$value] : $value;
}
print_r($result);
Output:
Array
(
[tensionat] => 3
[trist] => 4
[melancolic] => 1
[fara_speranta] => foarte puțin
[nefolositor] => 1
[ingrijorat] => 5
[amarat] => 1
[anxios] => 3
)

How to remove the duplicate data into array [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
Need help for the code.
Here is my list of array which i want to remove the two (2) Wi-fi.
Array
(
[20-10] => Array
(
[facilityCode] => 20
[facilityGroupCode] => 10
[order] => 1
[number] => 1968
[voucher] =>
[description] => Year of construction
)
[550-70] => Array
(
[facilityCode] => 550
[facilityGroupCode] => 70
[order] => 1
[indFee] =>
[indYesOrNo] => 1
[voucher] =>
[description] => Wi-fi
)
[20-60] => Array
(
[facilityCode] => 20
[facilityGroupCode] => 60
[order] => 1
[indLogic] => 1
[voucher] =>
[description] => Shower
)
[261-60] => Array
(
[facilityCode] => 261
[facilityGroupCode] => 60
[order] => 1
[indFee] =>
[indYesOrNo] => 1
[voucher] =>
[description] => Wi-fi
)
)
I do also tried the array_unique();
here is the result:
Array
(
[0] => Year of construction
[1] => Shower
[2] => Wi-fi
)
But i want to keep the facilityCode,facilityGroupCode,order,number etc.
Thanks for any help.
One liner is all can do your requirement,
$result = array_reverse(array_values(array_column(array_reverse($arr), null, 'description')));
Source link for your requirement.
//populate data
$mainArr = array();
$first = array(
"facilityCode" => 20,
"facilityGroupCode" => 10,
"order" => 1,
"number" => 1968,
"voucher" => "",
"description" => "Year of construction",
);
$second = array(
"facilityCode" => 550,
"facilityGroupCode" => 70,
"order" => 1,
"indFee" => "",
"indYesOrNo" => 1,
"voucher" => "",
"description" => "Wi-fi"
);
$mainArr["20-10"] = $first;
$mainArr["550-70"] = $second;
$mainArr["261-60"] = $second;
//get duplicates
$counter = 0;
$duplicates = array();
foreach ($mainArr as $key=>$val) {
$counter++;
if (in_array($key, $duplicates)) continue;
$i = 0;
foreach ($mainArr as $key1=>$val1) {
if ($i < $counter) {
$i++;
continue;
}
if ($val["description"] == $val1["description"]) {
array_push($duplicates, $key1);
}
}
}
//remove duplicates
foreach($duplicates as $key) {
unset($mainArr[$key]);
}
$itemRows = array(); // Your main array
$descriptionValues = array();
foreach ($itemRows as $itemKey => $itemRow) {
foreach ($itemRow as $key => $value) {
if ($key == 'description') {
if (in_array($value, $descriptionValues)) {
unset($itemRows[$itemKey]);
continue 2;
}
$descriptionValues[] = $value;
}
}
}

How to merge an array with child elements

I have an array with same customerid. I want to merge all same customerid arrays in to one with few amends to the array.
Array
(
[0] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[profession_id] => 8
[profession_name] => Producer
)
[1] => Array
(
[customerid] => 1
[customer_fullname] => John
[profession_id] => 8
[profession_name] => Producer
)
[2] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[profession_id] => 7
[profession_name] => Camera
)
)
So now I want a new array to be created like this:
Array(
[customerid] => 13
[customer_fullname] => Chris
[new_array] => array(
[0]=>[profession_id] => 8, [profession_name] => Producer,
[1]=>[profession_id] => 7, [profession_name] => Camera
)
)
Spent some time on it but wasn't able to get it right
There are better approaches if you're merging lots of records, but if you want a way to just merge two records as stated, I'd just do this:
$array1 = array(
'customerid' => 13
'customer_fullname' => 'John',
'profession_id' => 8,
'profession_name' => 'Producer'
);
$array2 = array(
'customerid' => 13
'customer_fullname' => 'John',
'profession_id' => 7,
'profession_name' => 'Director'
);
function merge_customers($customerA, $customerB)
{
$newCustomer = array();
if ($customerA['customerid'] == $customerB['customerid'])
{
$newCustomer['customerid'] = $customerA['customerid'];
$newCustomer['customer_fullname'] = $customerA['customer_fullname'];
$newCustomer['new_array'] = array(
array(
'profession_id' => $customerA['profession_id'],
'profession_name' => $customerA['profession_name']
),
array(
'profession_id' => $customerB['profession_id'],
'profession_name' => $customerB['profession_name']
)
);
return $newCustomer;
}
/* We can't merge these if they're different customers. */
return NULL;
}
The extended solution which is also well-suited for finding and "merging" multiple groups of entries which has same customerid. Used functions: array_filter, array_count_values, array_keys, array_walk, array_chunk and array_values:
// supposing $arr is your initial array
// finds which 'customerid' has multiple entries
$dupIds = array_filter(array_count_values(array_column($arr, "customerid")), function($v) {
return $v > 1;
});
$dupIds = array_keys($dupIds);
$result = [];
array_walk($arr, function($v) use(&$result, $dupIds) {
if (in_array($v['customerid'], $dupIds)) {
$parts = array_chunk($v, 2, true);
if (!isset($result[$v['customerid']])) {
$result[$v['customerid']] = $parts[0] + ['new_array' => [$parts[1]]];
} else {
$result[$v['customerid']]['new_array'][] = $parts[1];
}
}
});
print_r(array_values($result));
The output:
Array
(
[0] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[new_array] => Array
(
[0] => Array
(
[profession_id] => 8
[profession_name] => Producer
)
[1] => Array
(
[profession_id] => 7
[profession_name] => Camera
)
)
)
)
Quick hack, maybe there is a nicer solution.
Note: The second "for each" loop is only needed if there is the possibility that the arrays don't have the same fields.
function merge($array1, $array2){
$result = array();
foreach($array1 as $key => $value){
if(isset($array2[$key]) && $array2[$key]!=$array1[$key]){
$result[$key][]=$value;
$result[$key][]=$array2[$key];
}else{
$result[$key]=$value;
}
}
foreach($array2 as $key => $value){
if(!isset($result[$key])){
$result[$key] = $value;
}
}
return $result;
}
print_r(merge($array1, $array2));

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);
}

PHP: How can i combine 2 different array into one

Is there a way to combine 2 array into one array?
My first array shows the amount calculated money per day.
$ArrayBefore[] = $amountOfTransactions_prDayArrayBefore;
Output:
Array (
[0] => Array (
[09/02] => 102.83
[08/02] => 3852.49
[07/02] => 2619.23
[06/02] => 1135.24
[05/02] => 2391.4
[04/02] => 2376.15
[03/02] => 2760.05
[02/02] => 1946.41
)
)
My second array shows the amount transactions per day.
$ArrayTrans[] = $amountOfTransactions_prDayArrayTrans;
Output:
Array (
[0] => Array (
[09/02] => 2
[08/02] => 30
[07/02] => 30
[06/02] => 15
[05/02] => 36
[04/02] => 31
[03/02] => 28
[02/02] => 14
)
)
Is there a way to combine both of them to one array. I want them to look like this, so i can spit them out in a table.
Array (
[0] => Array (
[09/02] => 102.83 => 2
[08/02] => 3852.49 => 30
[07/02] => 2619.23 => 30
[06/02] => 1135.24 => 15
[05/02] => 2391.4 => 36
[04/02] => 2376.15 => 31
[03/02] => 2760.05 => 28
[02/02] => 1946.41 => 14
)
)
i call first array $a , second array $b
foreach ( $a[0] as $key=>$value )
{
$c[0]["$value"] = $b[0][$key];
}
and
$c = array (size=1)
0 =>
array (size=8)
'102.83' => int 2
'3852.49' => int 30
'2619.23' => int 30
'1135.24' => int 15
'2391.4' => int 36
'2376.15' => int 31
'2760.05' => int 28
'1946.41' => int 14
Use array_merge():
$result = array_merge($ArrayBefore, $ArrayTrans);
EDIT:
Understand that my php is rusty, but how about something along the lines of:
foreach($ArrayBefore[] as $key => $value) {
$tmpPair[$value] = $ArrayTrans[0][$key];
$newArray[$key] = $tmpPair;
}
You may also be able to simplify it
foreach($ArrayBefore[] as $key => $value) {
$newArray[$key][$value] = $ArrayTrans[0][$key];
}

Categories