Related
I want to separate a PHP array when they have a common prefix.
$data = ['status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6'];
I want each of them in separate variables like $status, $countries, $pms which will contain:
$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]
My Current code is taking 1.5 seconds to group them:
$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
}
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);
I want to know if is there any faster way to do this
This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.
For separating the value you can use: extract
Consider the following code:
$data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
$res = array();
foreach($data as $elem) {
list($key,$val) = explode(".", $elem, 2);
$res[$key][] = $val;
}
extract($res); // this will separate to var with the prefix name
echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
This snippet took less the 0.001 second...
Thanks #mickmackusa for the simplification
Add continue to each of the if's, so if it's one of them, it won't then run the other ones... not really needed in the last one as obviously the loops starts again anyway. Should save a tiny bit of time, but doubt it'll be as much as you probably want to save.
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
continue;
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
continue;
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
continue;
}
}
I'd use explode to split them.
something like this:
$arr = array("status" => [],"country" => [],"pm" => []);
foreach($data as $item){
list($key,$val) = explode(".",$item);
$arr[$key][] = $val;
}
extract($res); // taken from david's answer
and it's a much more readable code (in my opinion)
___ EDIT ____
as #DavidWinder commented, this is both not dynamic and will not result in different variables - look at his answer for the most complete solution for your question
Use Explode. Also is a good way to use $limit param for performance and avoiding wrong behavior on having other '.' in values.
$arr = [];
foreach($data as $item){
list($key,$val) = explode('.', $item, 2);
if (!$key || !$val) continue;
$arr[$key][] = $val;
}
var_dump($arr);
If it was me I would do it like so...
<?php
$data = array ('status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6');
$out = array ();
foreach ( $data AS $value )
{
$value = explode ( '.', $value );
$out[$value[0]][] = $value[1];
}
print_r ( $out );
?>
I'm not sure if this'll boost the performance but you could re-arrange your array in a way that each row has a heading and the corresponding value and then use array_column() to group which data you want.
This is an example of how you could group your data in such a way. (PHP 7.1.25+)
$groupedData = array_map(function($arg) {
[$key, $val] = explode('.', $arg); # for PHP 5.6 < 7.1.25 use list($key, $val) = explode(...)
return array($key => $val);
}, $data);
Then, you can pull out all of the country Id's like so:
$countries = array_column($groupedData, 'country');
Here is a live demo.
You can push data into their respective groups while destructuring. The only iterated function call is explode().
Creating individual variables for each group is a design flaw / mismanagement of array data.
Code: (Demo)
$result = [];
foreach ($data as $value) {
[$prefix, $result[$prefix][]] = explode('.', $value, 2);
}
var_export($result);
Output:
array (
'status' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'country' =>
array (
0 => '244',
1 => '24',
2 => '845',
),
'pm' =>
array (
0 => '4',
1 => '9',
2 => '6',
),
)
Use sscanf() if you want to directly/explicitly cast the numeric values as integers. Demo
I want to separate a PHP array when they have a common prefix.
$data = ['status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6'];
I want each of them in separate variables like $status, $countries, $pms which will contain:
$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]
My Current code is taking 1.5 seconds to group them:
$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
}
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);
I want to know if is there any faster way to do this
This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.
For separating the value you can use: extract
Consider the following code:
$data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
$res = array();
foreach($data as $elem) {
list($key,$val) = explode(".", $elem, 2);
$res[$key][] = $val;
}
extract($res); // this will separate to var with the prefix name
echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
This snippet took less the 0.001 second...
Thanks #mickmackusa for the simplification
Add continue to each of the if's, so if it's one of them, it won't then run the other ones... not really needed in the last one as obviously the loops starts again anyway. Should save a tiny bit of time, but doubt it'll be as much as you probably want to save.
foreach($data as $item){
if(strpos($item, 'status.') !== false){
$statuses[]= substr($item,7);
continue;
}
if(strpos($item, 'country.') !== false){
$countries[]= substr($item,8);
continue;
}
if(strpos($item, 'pm.') !== false){
$pms[]= substr($item,3);
continue;
}
}
I'd use explode to split them.
something like this:
$arr = array("status" => [],"country" => [],"pm" => []);
foreach($data as $item){
list($key,$val) = explode(".",$item);
$arr[$key][] = $val;
}
extract($res); // taken from david's answer
and it's a much more readable code (in my opinion)
___ EDIT ____
as #DavidWinder commented, this is both not dynamic and will not result in different variables - look at his answer for the most complete solution for your question
Use Explode. Also is a good way to use $limit param for performance and avoiding wrong behavior on having other '.' in values.
$arr = [];
foreach($data as $item){
list($key,$val) = explode('.', $item, 2);
if (!$key || !$val) continue;
$arr[$key][] = $val;
}
var_dump($arr);
If it was me I would do it like so...
<?php
$data = array ('status.1', 'status.2', 'status.3',
'country.244', 'country.24', 'country.845',
'pm.4', 'pm.9', 'pm.6');
$out = array ();
foreach ( $data AS $value )
{
$value = explode ( '.', $value );
$out[$value[0]][] = $value[1];
}
print_r ( $out );
?>
I'm not sure if this'll boost the performance but you could re-arrange your array in a way that each row has a heading and the corresponding value and then use array_column() to group which data you want.
This is an example of how you could group your data in such a way. (PHP 7.1.25+)
$groupedData = array_map(function($arg) {
[$key, $val] = explode('.', $arg); # for PHP 5.6 < 7.1.25 use list($key, $val) = explode(...)
return array($key => $val);
}, $data);
Then, you can pull out all of the country Id's like so:
$countries = array_column($groupedData, 'country');
Here is a live demo.
You can push data into their respective groups while destructuring. The only iterated function call is explode().
Creating individual variables for each group is a design flaw / mismanagement of array data.
Code: (Demo)
$result = [];
foreach ($data as $value) {
[$prefix, $result[$prefix][]] = explode('.', $value, 2);
}
var_export($result);
Output:
array (
'status' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'country' =>
array (
0 => '244',
1 => '24',
2 => '845',
),
'pm' =>
array (
0 => '4',
1 => '9',
2 => '6',
),
)
Use sscanf() if you want to directly/explicitly cast the numeric values as integers. Demo
So I have multiples empty arrays that I want to fill, let's say
$a_tab = [];
$b_tab = [];
$c_tab = [];
I have an array containing some data, let's say
$data = ['a' => 'foo', 'b' => 'bar', 'c' => 'foobar'];
I wanted to be able to do something like this :
foreach($data as $key => $value) {
$tab_name = $key . '_tab'; // so we have a variable that have the same name as one of the array we declared before
$$tab_name[$value] = $value; // this should add 'foo' into $a_tab, 'bar' in $b_tab and 'foobar' in $c_tab
}
But no value is ever added to any array...
Could someone explain me what did I do wrong ?
PS : if you don't want pseudo-code, here is the code that I had when I faced the issue :
// $tab is a parameter of the current function
$done_courses = []; // the array where we are going to put every courses that already have been added in one bifurcation tab
$regex_wz = '/\_werkzoekende/';
$regex_bd = '/\_bediende/';
$regex_op = '/\_outplacement/';
$bifurcation_keys = ['wz_tab' => $regex_wz, 'bd_tab' => $regex_bd, 'op_tab' => $regex_op];
// create the 3 arrays
$wz_tab = [];
$bd_tab = [];
$op_tab = [];
foreach($tab as $key => $value) {
foreach($bifurcation_keys as $tab_name => $regex) {
if(preg_match($regex, $key)) {
$n_k = preg_replace($regex, '', $key);
$$tab_name[$n_k] = $value;
if(!isset($done_courses[$n_k])) {
$done_courses[$n_k] = $n_k;
}
}
}
}
Did you try..
foreach($data as $key => $value) {
${$key.'_tab'}[$value] = $value;
}
I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)
I am trying to get my head around arrays.
The arrays should look like this:
$questions[$a] => array( [0] => No, comment1
[1] => Yes, comment2
[2] => No, comment3 )
$answer[$a] => array( [0] => No
[1] => Yes
[3] => No )
$comment[$a] => array( [0] => comment1
[1] => comment2
[3] => comment3 )
=========================================================================
SECOND EDIT: Need to execute this in the loop to create a third array -
if($answer[$a] == "Yes") { $display[$a] = "style='display:none'";
} else { $display[$a] = "style='display:block'"; }
This is what i have: (28th for minitech)
while ($a > $count)
{
if($count > 11) {
foreach($questions as $q) {
list($answer, $comments[]) = explode(',', $q);
if($answer === "Yes") {
$display[$a] = "style='display:none'";
} else {
$display[$a] = "style='display:block'";
}
$answers[] = $answer;
}
}
$a++;
}
If they are actually strings, explode works:
$answers = array();
$comments = array();
$display = array();
foreach(array_slice($questions, 11) as $question) {
list($answer, $comments[]) = explode(',', $question);
$display[] = $answer === 'Yes' ? 'style="display: none"' : 'style="display: block"';
$answers[] = $answer;
}
Here’s a demo!
Change your while loop to this
while ...
{
$parts = explode(',', $questions[$a]);
$answer[$a][] = trim($parts[0]);
$comment[$a][] = trim($parts[1]);
}
In your original code you were overwriting the $answer[$a] and $comment[$a] each time, not appending to the end of an array
$questions[$a] = array('Q1?' => 'A1', 'Q2?' => 'A2', 'Q3?' => 'A3');
foreach($questions[$a] as $key => $value)
{
$comment[$a][] = $key;
$answer[$a][] = $value;
}
This should work.
foreach ($questions[$a] as $key=>$value){
$temp = explode(',',$value);
$answer[$key] = $temp[0];
$comment[$key] = $temp[1];
}
$key will have 0,1,2 respectively. $value will have the values for each $question[$a](No,Comment1 ....)
Can't think of a funky one-liner, but this should do it:
foreach ($questions as $a => $entries) {
foreach ($entries as $k => $entry) {
$parts = array_map('trim', explode(',', $entry));
$answer[$a][$k] = $parts[0];
$comment[$a][$k] = $parts[1];
}
}
$questions = array( 0 => 'No,comment1',1 => 'Yes,comment2',2 => 'No,comment3' );
foreach($questions as $question)
{
$parts = explode(",",$question);
$answer[] = $parts[0];
$comment[] = $parts[1];
}
echo "<pre>";
print_r($answer);
print_r($comment);
Here is the right answer
foreach($questions as $key => $question){
foreach($question as $q => $data){
$data= explode(',',$data);
$comments[$key][$q] = $data[0];
$answer[$key][$q] = $data[1];
}
}
If the values in $questions are comma-separated strings you could use an array_walk function to populate your $answer and $comment arrays
$question = array(...); //array storing values as described
$answer = array();
$comment = array();
array_walk($question, function ($value, $key) use ($answer,$comment) {
$value_array = explode(',', $value);
$answer[$key] = $value_array[0];
$comment[$key] = $value_array[1];
});
Note that this is shown using an anonymous function (closure) which requires PHP >= 5.3.0. If you had a lower version of PHP, you would need to declare a named function, and declare $answer and $comment as globals in the function. I think this is a hacky approach (using globals like this) so if I was using PHP < 5.3 I would probably just use a foreach loop like other answers to your question propose.
Functions like array_walk, array_filter and similar functions where callbacks are used are often great places to leverage the flexibility provided by anonymous functions.