Handle only the dates of an array - php

How do I list only dates from an array.
Use this code:
do {
$integrantes[] = $row_rs['integrantes'];
} while ($row_rs = mysql_fetch_assoc($rs));
echo '<pre>';
print_r($integrantes);
echo '</pre>';
result:
Array
(
[0] => 2:2014-08-13,4:2014-08-13,6:2014-08-13,7:2014-08-13
[1] => 3:2014-08-13,5:2014-08-13,6:2014-08-13
)

One way to do it:
$integrantes = array(
'2:2014-08-13,4:2014-08-13,6:2014-08-13,7:2014-08-13',
'3:2014-08-13,5:2014-08-13,6:2014-08-13'
);
$result = array();
foreach($integrantes as $delimited) {
$records = explode(',', $delimited);
foreach ($records as $record) {
list($id, $date) = explode(':', $record);
$result[] = $date;
}
}
var_dump($result);
Output:
array(7) {
[0]=>
string(10) "2014-08-13"
[1]=>
string(10) "2014-08-13"
[2]=>
string(10) "2014-08-13"
[3]=>
string(10) "2014-08-13"
[4]=>
string(10) "2014-08-13"
[5]=>
string(10) "2014-08-13"
[6]=>
string(10) "2014-08-13"
}
Here is Codepad demo

Try this
while ($row_rs = mysql_fetch_assoc($rs)){
preg_match_all('/\d{4}\-\d{2}-\d{2}/', $row_rs['integrantes'], $matches);
$integrantes = array_merge($integrantes, $matches[0]);
}

Related

Keep text within quotation intact, while splitting text

I need the data in the string [$str] that is within quotes to not split.
In this case, "Accounting company" should be kept in one string, not spread.
<?php
$str =
'#PROGRAM "Accounting company" 98.2
#GENERATED 2020715 "SE"';
$data = explode("\n", $str);
foreach($data as &$value){
$value = preg_split("/\s+/", $value);
}
var_dump($data);
Result:
array(2) {
[0]=>
array(4) {
[0]=>
string(8) "#PROGRAM"
[1]=>
string(11) ""Accounting" // Unwanted split
[2]=>
string(8) "company"" // Unwanted split
[3]=>
string(4) "98.2"
}
[1]=>
&array(4) {
[0]=>
string(0) ""
[1]=>
string(10) "#GENERATED"
[2]=>
string(7) "2020715"
[3]=>
string(4) ""SE""
}
}
Wanted result:
array(2) {
[0]=>
array(4) {
[0]=>
string(8) "#PROGRAM"
[1]=>
string(18) ""Accounting company"
[2]=>
string(4) "98.2"
}
[1]=>
&array(4) {
[0]=>
string(0) ""
[1]=>
string(10) "#GENERATED"
[2]=>
string(7) "2020715"
[3]=>
string(4) ""SE""
}
}
You could use a SKIP FAIL pattern to skip matching values from an opening till closing double quote and then match 1+ horizontal whitespace chars to split on
"[^"]*"(*SKIP)(*FAIL)|\h+
Regex demo
$str =
'#PROGRAM "Accounting company" 98.2
#GENERATED 2020715 "SE"';
$data = explode("\n", $str);
foreach($data as &$value){
$value = preg_split("/\"[^\"]*\"(*SKIP)(*FAIL)|\h+/", $value);
}
print_r($data);
Output
Array
(
[0] => #PROGRAM
[1] => "Accounting company"
[2] => 98.2
)
Array
(
[0] =>
[1] => #GENERATED
[2] => 2020715
[3] => "SE"
)
If you don't want the empty entry in the second array, you could use the PREG_SPLIT_NO_EMPTY flag:
$value = preg_split("/\"[^\"]*\"(*SKIP)(*FAIL)|\h+/", $value, -1, PREG_SPLIT_NO_EMPTY);
Php demo
Here a solution without regex
$str =
'#PROGRAM "Accounting company" 98.2
#GENERATED 2020715 "SE"';
$quoted = false;
$index = 0;
$data = [];
$rows = explode("\n", $str);
foreach($rows as $row) {
$temp = [];
for ($i = 0; $i < strlen($row); $i++) {
if ($row[$i] === "\"") $quoted = !$quoted;
if ($row[$i] === " " && !$quoted) {
$index++;
continue;
}
$temp[$index] = ($temp[$index] ?? "") . $row[$i];
}
$data[] = array_values($temp);
}
var_dump($data);
Result
array(2) {
[0]=>
array(3) {
[0]=>
string(8) "#PROGRAM"
[1]=>
string(20) ""Accounting company""
[2]=>
string(4) "98.2"
}
[1]=>
array(3) {
[0]=>
string(10) "#GENERATED"
[1]=>
string(7) "2020715"
[2]=>
string(4) ""SE""
}
}
Demo
Still figuring out a regex solution though :)
In case you want to keep the empty element at [1][0]: Demo

Count multidimensional array

I have my main array:
array(6) {
[1]=> array(3) {
[0]=> string(15) "Extension"
[1]=> int(1)
[2]=> string(6) "3,00 "
}
[2]=> array(3) {
[0]=> string(32) "Physics "
[1]=> string(1) "1"
[2]=> string(6) "3,00 "
}
[3]=> array(3) {
[0]=> string(31) "Physics "
[1]=> int(1)
[2]=> string(6) "6,00 "
}
[4]=> array(3) {
[0]=> string(34) "Desk"
[1]=> int(4)
[2]=> string(8) "127,00 "
}
[5]=> array(3) {
[0]=> string(18) "assistance"
[1]=> int(1)
[2]=> string(7) "12,50 "
}
[6]=> array(3) {
[0]=> string(15) "Extension"
[1]=> int(1)
[2]=> string(6) "3,00 "
}
}
My expected output is:
Extension 2
Physics 2
Desk 1
Assistance 1
The result must be in an resultarray
How can I do? I tried with array_count_values function but don't work.
How can I stock answear:
I tried this code but It doesn't work
$tabrecap = array();
foreach($counts as $key=>$value){
//echo $key." qte".$value;
$tabrecap = array ($key,$value,$valueOption);
}
As you asked in comment,Please try this:-
<?php
$array = array( '1'=> array('0'=>"Extension", '1'=> 1, '2'=>"3,00 " ), '2'=> array('0'=>"Physics",'1'=>"1","3,00 " ),'3'=> array('0'=>"Physics",'1'=>1,"6,00 "),'4'=> array('0'=>"Desk",'1'=>4,"127,00 "),'5'=> array('0'=>"assistance",'1'=>1,"12,50 " ),'6'=> array('0'=>"Extension",'1'=>1,"3,00 "));
$count = array();
$i = 0;
foreach ($array as $key=>$arr) {
// Add to the current group count if it exists
if (isset($count[$i][$arr[0]])) {
$count[$i][$arr[0]]++;
}
else $count[$i][$arr[0]] = 1;
$i++;
}
print_r($count);
?>
Output:- https://eval.in/379176
Looping is the answer.
<?php
// untested
$counts = Array();
foreach( $array as $subArray ){
$value = $subArray[0];
$counts[ $value ] = ( isset($counts[ $value ]) )
? $counts[ $value ] + 1
: 1;
}
var_dump( $counts);
Just make a loop and use first item of each array as key :
$array = array(
array("Extension", 1, "3,00"),
array("Physics", "1", "3,00"),
array("Physics", 1, "6,00 ")
);
$count = array();
foreach($array as $a)
$count[$a[0]]++;
var_dump($count); // array(2) { ["Extension"]=> int(1) ["Physics"]=> int(2) }

How to flatten array in PHP?

I have an array that contains 4 arrays with one value each.
array(4) {
[0]=>
array(1) {
["email"]=>
string(19) "test01#testmail.com"
}
[1]=>
array(1) {
["email"]=>
string(19) "test02#testmail.com"
}
[2]=>
array(1) {
["email"]=>
string(19) "test03#testmail.com"
}
[3]=>
array(1) {
["email"]=>
string(19) "test04#testmail.com"
}
}
What is the best (=shortest, native PHP functions preferred) way to flatten the array so that it just contains the email addresses as values:
array(4) {
[0]=>
string(19) "test01#testmail.com"
[1]=>
string(19) "test02#testmail.com"
[2]=>
string(19) "test03#testmail.com"
[3]=>
string(19) "test04#testmail.com"
}
In PHP 5.5 you have array_column:
$plucked = array_column($yourArray, 'email');
Otherwise, go with array_map:
$plucked = array_map(function($item){ return $item['email'];}, $yourArray);
You can use a RecursiveArrayIterator . This can flatten up even multi-nested arrays.
<?php
$arr1=array(0=> array("email"=>"test01#testmail.com"),1=>array("email"=>"test02#testmail.com"),2=> array("email"=>"test03#testmail.com"),
3=>array("email"=>"test04#testmail.com"));
echo "<pre>";
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr1));
$new_arr = array();
foreach($iter as $v) {
$new_arr[]=$v;
}
print_r($new_arr);
OUTPUT:
Array
(
[0] => test01#testmail.com
[1] => test02#testmail.com
[2] => test03#testmail.com
[3] => test04#testmail.com
)

php preg_split split string conditionally

I need to split the following
$str = 'min(5,6,7,88),email'
$str= 'min(5,6,7,88),!email,max(6,5),alpha_numeric,required'//other possibilities
so it returns an array like so:
array(
[0]=>array(
[0]=>'min',
[1]=>array(5,6,7,88)
)
[1]=>array(
[0]=>'email'
)
)
is this possible ? btw email and min could be anything really , aswell as 5 6 7 88
I think preg_match is best suited for this particular case. However, preg_match alone cannot format the output as you want it.
preg_match('/(\w+)\(([0-9,]+)\),(\w+)+/', $str, $values);
$output = array(
array($values[1], explode(',', $values[2])),
array($values[3]),
);
Given the following:
$test = "min(5,6,7,88),email";
$_ = null;
if (preg_match('/^(?<first>\w+)\((?<array>(?:[0-9]+\x2C*)+)\)\x2C(?<last>\w+)$/',$test,$_))
{
$result = Array(
Array($_['first'],explode(',',$_['array'])),
Array($_['last'])
);
print_r($result);
}
Renders the following result:
Array
(
[0] => Array
(
[0] => min
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 88
)
)
[1] => Array
(
[0] => email
)
)
function parse($str) {
$str = str_replace(array('(',')'),"0x00",$str);
$strArray = explode("0x00",$str);
$tokens = array();
$tokenRef = 0;
foreach($strArray as $tokenID => $tokenValue) {
if (($tokenID % 2) == 1) {
--$tokenRef;
$tokens[$tokenRef++][1] = '('.$tokenValue.')';
} else {
$tokenList = explode(",",$tokenValue);
foreach($tokenList as $token) {
if ($token != '') {
$tokens[$tokenRef++][0] = $token;
}
}
}
}
return $tokens;
}
$str = 'min(5,6,7,88),email';
$split = parse($str);
echo '<pre>';
var_dump($split);
echo '</pre>';
echo '<br />';
$str = 'min(5,6,7,88),!email,max(6,5),alpha_numeric,required';
$split = parse($str);
echo '<pre>';
var_dump($split);
echo '</pre>';
echo '<br />';
Gives
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "min"
[1]=>
string(10) "(5,6,7,88)"
}
[1]=>
array(1) {
[0]=>
string(5) "email"
}
}
and
array(5) {
[0]=>
array(2) {
[0]=>
string(3) "min"
[1]=>
string(10) "(5,6,7,88)"
}
[1]=>
array(1) {
[0]=>
string(6) "!email"
}
[2]=>
array(2) {
[0]=>
string(3) "max"
[1]=>
string(5) "(6,5)"
}
[3]=>
array(1) {
[0]=>
string(13) "alpha_numeric"
}
[4]=>
array(1) {
[0]=>
string(8) "required"
}
}

PHP array_merge_recursive with numeric keys

So I'm suppose to build a multidimensional array dynamically from a text file, and everything works perfectly except that the numeric keys are screwing me over...
The text file looks something like this:
a=1
b.c=2
b.d.0.e=3
b.d.0.f=4
b.d.1.e=5
b.d.1.f=6
As the array_merge_recursive doesn't work with numeric keys, the output is like:
array(2) {
["a"]=>
string(3) "1"
["b"]=>
array(2) {
["c"]=>
string(3) "2"
["d"]=>
array(4) {
[0]=>
array(1) {
["e"]=>
string(9) "3"
}
[1]=>
array(1) {
["f"]=>
string(4) "4"
}
[2]=> array(1) {
["e"]=>
string(8) "5"
}
[3]=>
array(1) {
["f"]=>
string(9) "6"
}}}}
Is there any easy solution to make the output like...?
array(2) {
["a"]=>
string(3) "1"
["b"]=>
array(2) {
["c"]=>
string(3) "2"
["d"]=>
array(2) {
[0]=>
array(2) {
["e"]=>
string(9) "3"
["f"]=>
string(4) "4"
}
[1]=>
array(3) {
["e"]=>
string(9) "5"
["f"]=>
string(4) "6"
}}}}
Thanks
You could break each bit into its components and build up the array one step at a time.
$path = "b.d.0.e";
$val = 3;
$output = array();
$parts = explode(".", $path);
// store a pointer to where we currently are in the array.
$curr =& $output;
// loop through up to the second last $part
for ($i = 0, $l = count($parts); $i < $l - 1; ++$i) {
$part = $parts[$i];
// convert numeric strings into integers
if (is_numeric($part)) {
$part = (int) $part;
}
// if we haven't visited here before, make an array
if (!isset($curr[$part])) {
$curr[$part] = array();
}
// jump to the next step
$curr =& $curr[$part];
}
// finally set the value
$curr[$parts[$l - 1]] = $val;
My output, using the same input as yours:
Array (
[a] => 1
[b] => Array (
[c] => 2
[d] => Array (
[0] => Array (
[e] => 3
[f] => 4
)
[1] => Array (
[g] => 5
[h] => 6
)
)
)
)
Or you could use eval():
$raw_data = file($txt_file, FILE_IGNORE_NEW_LINES);
foreach ($raw_data as $line) {
list($keys, $value) = explode('=', $line);
$keys = explode('.', $keys);
$arr_str = '$result';
foreach ($keys as $key) {
if (ctype_digit($key)) {
$arr_str .= "[" . $key . "]";
} else {
$arr_str .= "['" . $key . "']";
}
}
eval($arr_str . ' = $value;');
}
print_r($result);
I know this is an old one, but the best solution I have found is to use array_replace_recursive. It will achieve what you are looking to do:
$start = array(
"600" => array("total" => 100),
"700" => array("total" => 200)
);
$finish = array(
"600" => array("average" => 25),
"700" => array("average" => 50)
);
$out = array_replace_recursive($start,$finish);
var_dump($out):
array(2) {
[600]=>
array(2) {
["total"]=>
int(100)
["average"]=>
int(25)
}
[700]=>
array(2) {
["total"]=>
int(200)
["average"]=>
int(50)
}
}

Categories