Creating an array from a string issue - php

I have a function that creates a multi-dimensional array from a string. Here's how the output looks like for each string:
Strings:
app.name.version
app.vendor
NOTE: These are strings that are being retrieved from a database
Output:
['app']['name']['version']
['app']['vendor']
and I assign them values accordingly. The problem arises when I include numbers in the string representing an index number of a sub array. Here's an example:
shifts.breaks.unpaid.0.description
shifts.breaks.unpaid.0.duration
shifts.breaks.unpaid.1.description
shifts.breaks.unpaid.1.duration
with output:
Array
(
[unpaid] => Array
(
[0] => Array
(
[description] => Lunch
)
[1] => Array
(
[duration] => 30
)
[3] => Array
(
[description] => Lunch 2
)
[4] => Array
(
[duration] => 30
)
)
)
Where it should normally look like:
Array
(
[unpaid] => Array
(
[0] => Array
(
[description] => Lunch
[duration] => 30
)
[1] => Array
(
[description] => Lunch 2
[duration] => 30
)
)
)
The only thing that remedies this is if I replace the numbers with anything but numerical values like the following:
shifts.breaks.unpaid.b0.description
shifts.breaks.unpaid.b0.duration
shifts.breaks.unpaid.b1.description
shifts.breaks.unpaid.b1.duration
Array
(
[unpaid] => Array
(
[b0] => Array
(
[description] => Lunch
[duration] => 30
)
[b1] => Array
(
[description] => Lunch 2
[duration] => 30
)
)
)
Here's the function that creates the arrays:
function toArray($keys, $value){
$array = array();
$ref = &$array;
while(count($keys) > 0){
$n = array_shift($keys);
if(!is_array($ref))
$ref = array();
$ref = &$ref[$n];
}
$ref = $value;
return $array;
}
Where $keys contains $keys = explode('.', "my.testing.string"); and here's the example I've been working with:
$strings = array (
"app.names.0.first"=> "Samuel",
"app.names.0.last"=> "Smith",
"app.names.1.first" => "Mary",
"app.names.2.last" =>"Kubik"
);
$list = array();
foreach($strings as $key => $name) {
$list[] = (toArray(explode('.', $key),$name));
}
print_r(call_user_func_array('array_merge_recursive', $list));
At this point, I'm not too sure if this has something to do with array_merge_recursive. Any help in correcting this would be great!

Well one solution I found was re-writing a new array_merge_recursive function without overwriting numeric keys.
function array_merge_recursive_new() {
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array) {
reset($base); //important
while (list($key, $value) = #each($array)) {
if (is_array($value) && #is_array($base[$key])) {
$base[$key] = array_merge_recursive_new($base[$key], $value);
} else {
$base[$key] = $value;
}
}
}
return $base;
}
Thanks to a user on php.net. This will produce the correct output when keys are numeric.

Related

php - check multidimensional array for values that exists in more than 1 subarray

Following simplified multidimensional array given:
$input = Array
(
[arr1] => Array
(
[0] => JAN2016
[1] => MAI2013
[2] => JUN2014
}
[arr2] => Array
(
[0] => APR2016
[1] => DEC2013
[2] => JUN2014
}
[arr3] => Array
(
[0] => JAN2016
[1] => MAI2020
[2] => JUN2022
}
)
I want to check for elements, that exists in more than 1 subarray. An ideal output would be:
$output = Array
(
[JUN2014] => Array
(
[0] => arr1
[1] => arr2
)
[JAN2016] => Array
(
[0] => arr1
[1] => arr3
)
)
I'm currently stucked in a nested foreach because i need to look all silblings of the outer foreach and don't know how to accomplish that.
foreach($input as $k=>$values)
{
foreach($values as $value)
{
//check if value exists in array k+1....n
//if true, safe to output.
}
}
You are almost all the way there
$new = [];
foreach($input as $k=>$values) {
foreach($values as $value) {
$new[$value][] = $k;
}
}
The $new array should look just as you want it
Extended solution which filters subarrays:
$newArray = [];
foreach($input as $k=>$values)
{
foreach($values as $value)
{
$newArray[$value][] = $k;
}
}
print_r(array_filter(
$newArray,
function($v) { return 1 < count($v); }
));
Sample fiddle here.

Combining Arrays while merging the values with the same key

I have two arrays with same amount of values. I need to combine them ( array1 value to key, array2 value as value) without losing the values of the second array due to duplicate key. when I use combine_array() as expected it just gets the last value of the second array with the same key.
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Desired result
Array
(
[1] => 1
[2] => Array(
[0]=>2
[1]=>3
)
[3] => 2
)
This code will meet your request
$array1 = array("0"=>1,"1"=>2,"2"=>2,"3"=>3);
$array2 = array("0"=>1,"1"=>2,"2"=>3,"3"=>4);
$array = array();
foreach($array1 as $key => $value){
if($value != $array2[$key]){
$array[$key][] = $value;
$array[$key][] = $array2[$key];
}else{
$array[$key] = $value;
}
}
print_r($array);
The desired result is
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
)
)
I'm sure there are way better solutions than this, but it does the job for now. I would appreciate if someone can send a better written solution.
$combined = array();
$tempAr = array();
$firstMatch = array();
$count = 0;
foreach ($array1 as $index => $key) {
if (array_key_exists($key, $combined)) {
$tempAr[] = $array2[$index];
$count++;
} else {
$totalCount = $count;
}
if (!array_key_exists($key, $firstMatch)) {
$firstMatch[$key] = $array2[$index];
}
$output = array_slice($tempAr, $totalCount);
$combined[$key] = $output;
}
$combined = array_merge_recursive($firstMatch, $combined);

PHP Group array by values

I have an array like this:
Array (
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
[4] => ing_2_ing
[5] => ing_2_amount
[6] => ing_2_det
[7] => ing_2_meas
)
And I want to group the values into an array like this:
Array (
[0] => Array(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[1] => Array(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
There may be many other items named like that: ing_NUMBER_type
How do I group the first array to the way I want it? I tried this, but for some reason, strpos() sometimes fails:
$i = 1;
foreach ($firstArray as $t) {
if (strpos($t, (string)$i)) {
$secondArray[--$i][] = $t;
} else {
$i++;
}
}
What is wrong? Can you advice?
It depends what you are trying to achieve, if you want to split array by chunks use array_chunk method and if you are trying to create multidimensional array based on number you can use sscanf method in your loop to parse values:
$result = array();
foreach ($firstArray as $value)
{
$n = sscanf($value, 'ing_%d_%s', $id, $string);
if ($n > 1)
{
$result[$id][] = $value;
}
}
<?php
$ary1 = array("ing_1_ing","ing_1_amount","ing_1_det","ing_1_meas","ing_2_ing","ing_2_amount","ing_2_det","ing_2_meas");
foreach($ary1 as $val)
{
$parts = explode("_",$val);
$ary2[$parts[1]][]=$val;
}
?>
This creates:
Array
(
[1] => Array
(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[2] => Array
(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
What I'd do is something like this:
$result = array();
foreach ($firstArray as $value)
{
preg_match('/^ing_(\d+)_/', $value, $matches);
$number = $matches[1];
if (!array_key_exists($number, $result))
$result[$number] = array();
$result[$number][] = $value;
}
Basically you iterate through your first array, see what number is there, and put it in the right location in your final array.
EDIT. If you know you'll always have the numbers start from 1, you can replace $number = $matches[1]; for $number = $matches[1] - 1;, this way you'll get exactly the same result you posted as your example.

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Comparing multiple different dates and getting the average in PHP

I use a function called count_days($date1,$date2) that counts the number of days between two dates. But, my question is: the dates come from the DB, in an array like:
Array (
[imac] => Array (
[0] => 2002-10-10
[1] => 2003-11-22
[3] => 2004-11-10
)
[iphone] => Array (
[0] => 2007-09-11
[1] => 2008-05-12
[2] => 2009-06-14
[3] => 2010-06-05
)
)
As you can see the products may have a different number of subarrays. I want to count the days between the first and the next date (and so on!) and then get the average of days.
The DateInterval class is great for this kind of date arithmetic. You can use DateTime::add, DateTime::subtract and DateTime::diff to work with them.
<?php
$types = array(
'imac' => array ('2002-10-10', '2003-11-22', '2004-11-10'),
'iphone' => array ( '2007-09-11', '2008-05-12', '2009-06-14', '2010-06-05'),
);
$typeIntervals = array();
$typeAverage = array();
foreach ($types as $type=>$dates) {
$last = null;
$typeIntervals[$type] = array();
foreach ($dates as $date) {
$current = new DateTime($date);
if ($last) {
$interval = $current->diff($last);
$typeIntervals[$type][] = $interval->days;
}
$last = $current;
}
$typeAverage[$type] = array_sum($typeIntervals[$type]) / count($typeIntervals[$type]);
}
print_r(typeIntervals);
print_r($typeAverage);
This will output:
Array (
[imac] => Array (
[0] => 408
[1] => 354
)
[iphone] => Array (
[0] => 244
[1] => 398
[2] => 356
)
)
Array (
[imac] => 381
[iphone] => 332.66666666667
)
try smth like this ( not tested )
$lastDate = $dbArray[0][0];
$daysArray = array();
foreach ( $dbArray as $value )
{
if ( is_array($value) )
{
foreach ( $value as $v )
{
$daysArray[] = count_days($lastDate, $v);
$lastDate = $v;
}
} else {
//not an array check if it's a date and test it here
}
}
$average = array_sum($daysArray)/count($daysArray);

Categories