Is it possible to create a new array from the keys of another like following?
it is a dynamic array chk_values are dynamically changed depends on condition
Array
(
[actBtn] => update
[chkCount] => 5
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
and i want array like this for update database
$chckpoint = Array(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3)
Simply process the original array and only move to the new array where the key starts with chk_
$in = ['actBtn' => 'update',
'chkCount' => 5,
'chk_1' => 2,
'chk_2' => 3,
'chk_3' => 2,
'chk_4' => 3,
'chk_5' => 3
];
foreach($in as $k=>$v){
if ( strpos($k,'chk_') !== false ){ $chckpoint[$k] = $v; }
}
print_r($chckpoint);
RESULT
Array
(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
You can simply take the input array and check for all keys beginning with chk_. If the key matches, take it to the new array.
$chckpoint = [];
foreach($input as $key => $value)
{
if(substr($key, 0, 4) == 'chk_') $chkpoint[$key] = $value;
}
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.
First of all this is not a duplicate question as i have tried most of the stack answer.
I have about 138886 records in my array.
records are like
[1] => Array
(
[country] => US
[state] => Albama
[city] => Brest
[postcode] => 225001-225003
[shipping_info] => Delivery Available
[is_zip_range] => 1
[zip_from] => 225001
[zip_to] => 225003
)
[2] => Array
(
[country] => BY
[state] => Brest
[city] => Brest
[postcode] => 225001-225003
[shipping_info] => Delivery Available
[is_zip_range] => 1
[zip_from] => 225001
[zip_to] => 225003
)
I want to unique all record from postcode value i have tried some method are
Method 1
$temp = array_unique(array_column($data, 'postcode'));
$filteredData = array_intersect_key($data, $temp);
but it is still giving duplicate value.
Method 2
$filteredData = array_map("unserialize", array_unique(array_map("serialize", $data)));
this is won't work
Method 3
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$details = unique_multidim_array($array,'postcode');
It is working but too slow taking about 2/3 mins.
let me know any other method i can use for unique array.
help will be apprecitaed
Why are you making it so hard,
$in = array (
1 =>
array (
'country' => 'US',
'state' => 'Albama',
'city' => 'Brest',
'postcode' => '225001-225003',
'shipping_info' => 'DeliveryAvailable',
'is_zip_range' => 1,
'zip_from' => 225001,
'zip_to' => 225003
),
2 =>
array (
'country' => 'BY',
'state' => 'Brest',
'city' => 'Brest',
'postcode' => '225001-225003',
'shipping_info' => 'DeliveryAvailable',
'is_zip_range' => 1,
'zip_from' => 225001,
'zip_to' => 225003
)
);
$out = [];
foreach($in as $i) if(!isset($out[$i['postcode']])) $out[$i['postcode']] = $i;
Sandbox
You can do the same thing with in_array, but the isset is faster.
In fact you dont even need to do the isset
foreach($in as $i) $out[$i['postcode']] = $i;
Array keys are always unique, but this will retain the last duplicate where as the previous code keeps the first one.
And if the keys bug you latter just do $out = array_values($out) to reset them.
I i'm developing php application. I have used Google Chart API for display charts.
I have select and returned necessary data for chart.
I got following array as my output.
print_r($output);
//Out put
Array
(
[0] => Array
(
[month] => April
[sec_id] => 2
[sec_name] => Commerce
[count] => 1
)
[1] => Array
(
[month] => June
[sec_id] => 2
[sec_name] => Commerce
[count] => 3
)
[2] => Array
(
[month] => July
[sec_id] => 2
[sec_name] => Commerce
[count] => 1
)
[3] => Array
(
[month] => August
[sec_id] => 4
[sec_name] => Science
[count] => 3
)
[4] => Array
(
[month] => August
[sec_id] => 3
[sec_name] => Maths
[count] => 2
)
[5] => Array
(
[month] => August
[sec_id] => 1
[sec_name] => Art
[count] => 2
)
[6] => Array
(
[month] => August
[sec_id] => 2
[sec_name] => Commerce
[count] => 2
)
)
print_r(json_encode($output)); // return above array as output
I request above data using ajax ( data type is JSON)
I want to return data as bellow to generate google chart.
[
['Month', 'Art', 'Commerce', 'Maths', 'Sience'],
['April', '', 2, '', ''],
['June', '', 3, '', ''],
['July', '', 1, '', ''],
['August', 2, 2, 3, 3]
]
I tried this this code
$output = array();
$output[0] = array('Month', 'Art', 'Commerce', 'Maths', 'Science');
foreach($records as $key=> $record){
$art =''; $commerce =''; $maths=''; $science='';
if($record['sec_id'] == 1){
$art = $record['count'];
}else if($record['sec_id'] == 2){
$commerce = $record['count'];
}else if($record['sec_id'] == 3){
$maths = $record['count'];
}else if($record['sec_id'] == 4){
$science = $record['count'];
}
$output[++$key] = array(0 => $record['month'], 1 => $art, 2 => $commerce, 3 => $maths, 4 => $science);
}
function super_unique($array){
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value){
if ( is_array($value)){
$result[$key] = super_unique($value);
}
}
return $result;
}
$output = super_unique($output);
Out put was
[["Month","Art","Commerce","Maths","Science"],["April","","1"],["June","","3"],["July","","1"],{"0":"August","1":"","4":"3"},{"0":"August","1":"","3":"2"},["August","2",""],["August","","2"]]
This is pretty straightforward to loop through and reorganize, particularly since your sec_ids match up nicely with the array indices.
Example:
$temp = array();
$output = array(
array('Month', 'Art', 'Commerce', 'Maths', 'Science')
);
foreach ($records as $record) {
$month = $record["month"];
$sec_id = $record["sec_id"];
$count = $record["count"];
if (!isset($temp[$month])) {
$temp[$month] = array_fill(0, 5, '');
}
$temp[$month][0] = $month;
$temp[$month][$sec_id] += $count;
}
$output = array_merge($output, array_values($temp));
echo json_encode($output);
Output:
[["Month","Art","Commerce","Maths","Science"],["April","",2,"",""],["June","",3,"",""],["July","",1,"",""],["August",2,2,2,3]]
Let's rethink your algorithm. As you go through each element in records, we need to ask two things: what data are we pulling out and what do we want to do with it?
The first question is simple: we're just pulling out the value 'count'.
The second question is going to determine our algorithm. What we want to do is take that 'count' value, and stick it a particular spot in our ourpur array.
Looking at the output array as a table, we can see that the desired position of 'count' is determined by the 'month' field (which determines the row) and by the 'sec_id'/'sec_name' fields (which determine the column). So what you want your loop to look like is this...
foreach($records as $record)
{
$output[$record['month']][$record['sec_id']] = $record['count']
}
The first caveat to this is that for each unique month, you do still need to create and initialize the sub-array, and you must do it only once. So, the loop becomes.
foreach($records as $record)
{
if(!is_array($output[$record['month']]))
$output[$record['month']] = array(0 => $record['month'], 1 => '', 2 => '', 3 => '', 4 => '');
$output[$record['month']][$record['sec_id']] = $record['count']
}
Finally, we used the actual month name as the keys in the top-level array. To comply with the numeric-only keys specified in your desired output, we can ditch those keys with the following piece of code.
$output = array_values($output)
If I'm right in thinking you were trying to use super_unique() to combine rows with the same month, that's not what it was doing at all. Firstly, array_unique() doesn't combine rows, it eliminates duplicates. Since you were comparing serialized rows, rather than just looking at the month field, none of your rows were duplicates, so that function was doing nothing. Furthermore, since several of your array fields were set to '', the serialize/unserialize process was actually causing those fields to get dropped, which is why you were ending up with sub-arrays of less than five elements, and with associative keys.
I need to merge a new array of alternative information into the loop if they have the alternative information in their profile.
Here's my loop:
foreach ($doctor->getVars() as $k => $v)
{
$data['doctor_'. $k] = $v;
}
foreach ($patient->get_data() as $k=>$v)
{
if (is_string($v) || is_numeric($v))
$data["patient_" . $k] = strtoupper($v);
}
Here's the $data var_dump:
Array
(
[employee] => person
[date] => 05/08/2013
[datetime] => 05/08/2013 9:41:15 AM
[department] => stuff
[employee_ext] => 7457
[employee_email] =>
[barcode] => *NZS01*
[doctor_df_code] => 09HQ
[doctor_npi] => 1111111111
[doctor_dea] => B4574
[doctor_upin] =>
[doctor_license] =>
[doctor_phone] => (111)111-1111
[doctor_fax] => (000)000-0000
[doctor_fname] => UNDEFINED
[doctor_lname] => UNDEFINED
[doctor_title] =>
[doctor_intake_rx_caller_id] =>
[doctor_costco_rx_caller_id] =>
[doctor_reorder_rx_caller_id] =>
[doctor_address1] => 24 CABELL st
[doctor_address2] => SUITE 10
[doctor_city] => places
[doctor_state] => CA
[doctor_zip] => 91111
[doctor_active_events] =>
[doctor_dont_call] => 0
[doctor_dont_fax] => 1
)
I need to merge the below array into the above array.
Here's the print var for the function addr($dfcode):
Array
(
[0] => Array
(
[CODE_] => 09HQ
[doctor_address1] => alternate addy
[doctor_address2] => 45854
[doctor_city] => different city
[doctor_state] => CA
[doctor_zip] => 963545
[doctor_phone] => (619)111-2548
[doctor_fax] => (157)123-4569
)
)
I'm new to array merge and I'm assuming right after the $data['doctor_'. $k] = $v i could list out the new function and the fields i want to merge in particular?
syntax is what i'm not sure on:
$data['doctor_'. $k] . array_merge(addr($dfcode))['doctor_address1'] = $v;
Any help would be greatly appreciated, thank you.
The general formula for merging two arrays is as follows (merging $array_m into $array_o):
foreach($array_m as $key=>$value){
$array_o[$key] = $value;
}
$array_o would now contain all of the elements of $array_m
EDIT: I just noticed in your post that you seem to want to use the array_merge function. You could also do the following:
$array_o = array_merge($array_o, array_m);
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