Currently I have a file that looks something like this:
Awesomedude123 = 399,408 = September 16, 2012:
Username11 = 1,914,144 = September 16, 2012:
EpicSurfer = 1,031,427 = September 16, 2012:
What I want to do is transform it into a multidimensional array with PHP so it looks something like this:
Array
(
[1] => Array
(
[0] => Awesomedude123
[1] => 399,408
[2] => September 16, 2012
)
[2] => Array
(
[0] => Username11
[1] => 1,914,144
[2] => September 16, 2012
)
[3] => Array
(
[0] => EpicSurfer
[1] => 1,031,427
[2] => September 16, 2012
)
)
I have tried using array_shift, but it didn't work out. Any help would be HIGHLY appreciated!
Here is the code:
<?php
$data = file_get_contents('File.txt'); // Get the file content
$data = str_replace(array("\n", "\r"), '', $data); // Clear newline characters
$data = explode(':', $data); // Get each record by : at end of line
unset($data[count($data) - 1]); // Clear the last empty element
$final_array = array();
foreach($data AS $row){ // Loop the exploded data
$final_array[] = explode(' = ', $row); // Explode each row by Space=Space to each row of final_array
}
print_r($final_array);
?>
You can use a regular expression to split your string:
myarray = array();
$file = fopen("myfile",'r');
while (!feof($file)) {
$line = fgets($file);
preg_match("/(\w+) = (.+) = (.+)/",$line,$matches);
myarray[] = array($matches[1],$matches[2],$matches[3]);
}
Related
I am using PHP 7.3.5 and I have the following set of array values:
$valueArr = ['-4.2%', '51.0', '90K', '0.5%', '0.74|2.6', '-1.2B', '779B', '215K', '92.2%', '42.8B', '1.49T', '1690B', '-10.8B', '0.38|3.9', '102.4', '1.00%', '0.07|1.3'];
Basically I want for each of these values the number and the "type", so if it is a percentage then I would like to get -4.2 and percentage.
I tried to create a minimum example (however the below code is no real good example ;( ), but I am stuck at the data structure level as some array keys have two inputs, such as '0.74|2.6':
<?php
$valueArr = ['-4.2%', '51.0', '90K', '0.5%', '0.74|2.6', '-1.2B', '779B', '215K', '92.2%', '42.8B', '1.49T', '1690B', '-10.8B', '0.38|3.9', '102.4', '1.00%', '0.07|1.3'];
$resArr = array();
$structureArr = array(
'value1' => "",
'number1' => "",
'value2' => "",
'number2' => ""
);
foreach ($valueArr as $key => $v) {
if (1 === preg_match('/%/', $valueArr[$key])) {
preg_match('!\d+\.*\d*!', $valueArr[$key], $structureArr['number1']);
$structureArr['value1'] = 'percentage';
}
/*
if (1 === preg_match('|', $valueArr[$key])) {
$str = explode("|", $valueArr[$key]);
$value1 = 'number';
$number1 = $str[0];
$value2 = 'number';
$number2 = $str[1];
}
if (1 === preg_match('', $valueArr[$key])) {
}
*/
array_push($resArr, $structureArr);
}
print_r($resArr);
/*
Wanted Result
Array
(
[0] => Array
(
[0] => -4.2
[1] => 'percentage'
)
[1] => Array
(
[0] => 51.0
[1] => 'number'
)
[2] => Array
(
[0] => 90000
[1] => number
)
[3] => Array
(
[0] => 0.5
[1] => percentage
)
[4] => Array
(
[0] => 0.74
[1] => number
[2] => 2.6
[3] => number
)
...
*/
I would highly appreciate your input on how to structure this array input.
Appreciate your replies!
If you join the array on a space and replace pipes | with a space, then you have a list of numbers and their symbol (if any) separated by a space. Then just match your numbers and whatever symbol comes after it. Then you just match the number index with the symbol index. I used an array to map the symbol to the word and number if none:
$string = str_replace('|', ' ', implode(' ', $valueArr));
preg_match_all('/([\d.-]+)([^\s]*)/', $string, $matches);
$types = ['%'=>'percent','K'=>'thousand','M'=>'million','B'=>'billion','T'=>'trillion'];
foreach($matches[1] as $k => $v) {
$t = $types[$matches[2][$k]] ?? 'number';
$result[] = [$v, $t];
}
This yields an array like this, with each number that was joined by a pipe with it's own element:
Array
(
[0] => Array
(
[0] => -4.2
[1] => percent
)
[1] => Array
(
[0] => 51.0
[1] => number
)
[2] => Array
(
[0] => 90
[1] => thousand
)
///etc...
If you need a floating point number then just change:
$result[] = [(float)$v, $t];
This expands on my comment. Not sure if it's the most optimal solution or not.
Rough outline...
Create array mapping suffix to multiplier. Loop through source array. explode on |. Loop through result. If last character is %, strip it, value=value and type=percentage, else, strip last char, use it as array index (if it is an available index), value=value*multiplier and type=number.
$resArr = array();
$multipliers = array("K" => 1000, "M" => 1000000, "B" => 1000000000, "T" => 1000000000000);
$valueArr = ['-4.2%', '51.0', '90K', '0.5%', '0.74|2.6', '-1.2B', '779B', '215K', '92.2%', '42.8B', '1.49T', '1690B', '-10.8B', '0.38|3.9', '102.4', '1.00%', '0.07|1.3'];
foreach($valueArr as $index => $value)
{
$parts = explode("|", $value);
$resArr[$index] = array();
foreach($parts as $part)
{
$lastChar = substr($part, -1);
if($lastChar == "%")
{
$resArr[$index][] = substr($part, 0, -1);
$resArr[$index][] = "percentage";
}
else if(in_array($lastChar, array_keys($multipliers)))
{
$multiple = $multipliers[$lastChar];
$resArr[$index][] = (substr($part, 0, -1))*$multiple;
$resArr[$index][] = "number";
}
else
{
$resArr[$index][] = $part;
$resArr[$index][] = "number";
}
}
}
var_dump($resArr);
DEMO
I need values from my database to plot a graph.
I have multiple lines I want to plot on the same graph.
I need the values, for each line, in the following form, for as many different $dates there are in the database:
$graph_points1 = array(array($date, $value), array($date, $value), array($date, $value));
I have a query to get the data from the database:
$data = $wpdb->get_results($wpdb->prepare( "SELECT * FROM `wp_graph_info` ORDER BY DATE ASC"));
If I use the following code:
foreach($data as $datas){
$list_name = $datas->list_name;
$date = $datas->date;
$value = $datas->subscriber_count;
if($list_name == 'line1'){
$result = array(array($date,$value));}}
print_r($result); will give:
Array ( [0] => Array ( [0] => 2015-05-16 [1] => 131 ) )
Array ( [0] => Array ( [0] => 2015-05-17 [1] => 133 ) )
Array ( [0] => Array ( [0] => 2015-05-18 [1] => 137 ) )
which is almost what I want.
I need to have the results as:
$graph_points1 = array(array(2015-05-16, 131), array(2015-05-17, 133), array(2015-05-18, 137));
how to I put it in the above form?
Also I can't plot the date on the x-axis. How do I only retrieve the 'day' value so I have:
$graph_points1 = array(array(16, 131), array(17, 133), array(18, 137));
Also if there a way to loop through all th $list_names (I have 7 different lists, so my graph will plot 7 lines) or do I need to use an if() statement for each one?
$result = [];
foreach($data as $datas){
$list_name = $datas->list_name;
$date = $datas->date;
$value = $datas->subscriber_count;
list($year, $month, $day) = explode('-', $date);
$result[$list_name][] = array($day,$value);
}
echo "<pre>";var_dump($result);echo "</pre>";
I have a text file countries.txt with a list of all countries:
1. Australia
2. Austria
3. Belgium
4. US
I want to create an array in country_handler.php like this:
$countries = array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
How to do that?
Better you can use this in a function like below - then just called this function from any where
function getCountryList()
{
return array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
}
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL, $data);
$file = file('countries.txt');
$countries = array();
foreach ($file as $line) {
#list ($index, $country) = explode('.', $line);
$countries[trim($index)] = trim($country);
}
print_r($countries);
$lines = file('countries.txt');
$newArr = array();
foreach ($lines as $line) {
$erg = preg_split('/\.\s+/', $line);
$newArr[$erg[0]] = $erg[1];
}
var_dump($newArr);
Luckily (sometimes) regex doesn't include newlines in the ., so you can do this:
$contents = file_get_contents('countries.txt');
preg_match_all('#(\d+)\.\s+(.+)#', $contents, $matches);
print_r($matches);
The regex means:
(\d+) -- a number (save this)
\. -- a literal dot
\s+ -- white space
(.+) -- any character except \n or \r (end-of-line) (save this)
Which results in:
Array
(
[0] => Array
(
[0] => 1. Australia
[1] => 2. Austria
[2] => 3. Belgium
[3] => 4. US
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[2] => Array
(
[0] => Australia
[1] => Austria
[2] => Belgium
[3] => US
)
)
and I'm sure from [1] and [2] you can make the keyed array you need.
array_combine to the easy rescue:
$countries = array_combine($matches[1], $matches[2]);
Try this:
<?php
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL,$data);
$cnt = 1;
foreach($countries as $val) {
if($val <>"") {
$res[$cnt] = strstr(trim($val), ' ');
$cnt++;
}
}
print_r($res);
?>
I am working within a foreach loop and PARTS my code looks like this:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
The Output result of the above is this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
Yes I see there are similar questions to this. But none of their answers seem to work for me. I'm thinking it might be because I am working inside an foreach loop. Either way, I was wondering if there was a way to get my output above to look like this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
All the duplicates gone, without loosing the formatting of this array. Code I have tried.. but "maybe" wrong was:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
EDIT for Sharanya Dutta:
I have alot of other code, but basically this is where Im trying to use it.
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
Use an array ($arr in the following code) to store the values and print_r only those values which are different from the already stored values:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
DEMO
You may even use $diff after the last line in the foreach loop:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}
DEMO
As you iterate the result set rows and explode the text string, filter the individual values in the current row against all values in all previously encountered rows.
If there are any individual values encountered for the first time, then save the unique values of that row as a new row in the result array.
Code: (Demo)
$resultSet = [
['text' => 'Charcoal,Natural Gas,Combo'],
['text' => 'Charcoal,Propane,Combo'],
['text' => 'Charcoal,Propane,Natural Gas,Combo'],
['text' => 'coal'],
['text' => 'Natural Gas,wood'],
];
$result = [];
foreach ($resultSet as $row) {
$clean = array_diff(
explode(',', $row['text']),
...$result
);
if ($clean) {
$result[] = array_values($clean);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'Charcoal',
1 => 'Natural Gas',
2 => 'Combo',
),
1 =>
array (
0 => 'Propane',
),
2 =>
array (
0 => 'coal',
),
3 =>
array (
0 => 'wood',
),
)
I have a .txt file that looks like the one below:
Test = 10849831 = August 6, 2013:
56cake = 0 = August 6, 2013:
Wwe = 812986192 = August 6, 2013:
I want to explode the file above to make an array that looks like the one below:
Array
(
[Test] => Array
(
[0] => 10849831
[1] => August 6, 2013
)
[56cake] => Array
(
[0] => 0
[1] => August 6, 2013
)
[Wwe] => Array
(
[0] => 812986192
[1] => August 6, 2013
)
)
How can I accomplish this? I've already tried using something like explode(":", $data) but I don't know how to use it to do what I want above. I'm fairly new with PHP.
Just a little bit of array iteration does the trick with: explode, array_map, trim, isset and foreach.
PHP Example
$txt = <<<DOC
Test = 10849831 = August 6, 2013:
56cake = 0 = August 6, 2013:
Wwe = 812986192 = August 6, 2013:
DOC;
$Output = array();
$Lines = explode(":", $txt);
foreach($Lines as $line) {
$Rows = array_map('trim', explode(" = ", $line));
if(!isset($Rows[0], $Rows[1], $Rows[2])) continue;
$Output[$Rows[0]] = array($Rows[1], $Rows[2]);
}
print_r($Output);
PHP Code Output
Array
(
[Test] => Array
(
[0] => 10849831
[1] => August 6, 2013
)
[56cake] => Array
(
[0] => 0
[1] => August 6, 2013
)
[Wwe] => Array
(
[0] => 812986192
[1] => August 6, 2013
)
)
The Code Explained
Break up the lines with explode(":", $txt)
Loop through each line and break up each section by = again using explode
Use array_map to cycle each value and remove whitespace
Check to ensure we have 3 values with isset, if not, then skip the iteration
Push our collected values into the output array
Something like this?
<?php
// Sample text data
$text = 'Test = 10849831 = August 6, 2013:
Test = 10849831 = August 6, 2013:
56cake = 0 = August 6, 2013:
Wwe = 812986192 = August 6, 2013:';
$text = explode( PHP_EOL, $text ); // split by lines using linebreaks
// $text = explode( ":", $text ); // you can also split by lines with ':'
$arr = array(); // Our array which holding the output
// print_r( $text );
foreach( $text as $line ) { // loop through lines
$line = array_map( "trim", explode( "=", $line ) ); // split by '=' sign and do 'trim'
// print_r( $line );
if ( count( $line ) === 3 ) {
$key = strtolower( $line[0] ); // make the key lowercase (case insensitive)
$val1 = $line[1];
// process the date and remove day from date
$val2 = trim( $line[2], ":" ); // remove ':' from the end of date
$val2 = array_map( "trim", explode( " ", $val2 ) ); // split by space sign and do a 'trim'
$val2 = $val2[0]." ".$val2[2]; // join year and month parts
if ( isset( $arr[$key] ) ) { // check if the key already exists
// key exists, push new values
array_push( $arr[$key], $val1, $val2 );
continue; // key exists so continue the loop
}
// key doesn't exists in array so add the values
$arr[$key] = array( $val1, $val2 );
}
}
// there is an altwernate way to remove duplicate values using 'array_unique'
// uncomment below code if you dont want duplicate values
/*if ( !empty( $arr ) ) {
$arr = array_map( "array_unique", $arr ); // remove duplicate values from array using 'array_unique'
}*/
print_r( $arr );
?>
Here is the list of functions which i used in my code and link to those functions documentation
explode
array_map
trim
count
strtolower
isset
array_push
array_unique
Try to re-use this code:
<?php
echo '<pre>';
$result = array();
$string = 'Test = 10849831 = August 6, 2013';
$temp1 = explode("=", $string, 2);
print_r($temp1);
/*
Array
(
[0] => Test
[1] => 10849831 = August 6, 2013
)
*/
$key = $temp1[0];
$result[$key] = explode("=", $temp1[1]);
print_r($result);
/*
Array
(
[Test ] => Array
(
[0] => 10849831
[1] => August 6, 2013
)
)
*/
?>
$chunks = explode(':', $text);
$out = array();
foreach ($chunks as $key => $value){
$parts = explode('=', $value);
if (count($parts) == 3){
$out[trim($parts[0])] = array(trim($parts[1]), trim($parts[2]));
}
}
print_r($out);
You have use explode like this:
<?php
//
//Test = 10849831 = August 6, 2013:
//56cake = 0 = August 6, 2013:
//Wwe = 812986192 = August 6, 2013:
function read_data_file( $file ) {
$file_open = fopen( $file , 'r' );
$file_data = fread( $file_open , filesize( $file ) );
fclose( $file_open );
return $file_data;
}
$result_read = read_data_file('/home/josecarlos/Desktop/test.txt');
$result_explode = explode("\n", $result_read );
$final_result = array();
foreach ($result_explode as $key => $cursor){
$explode = explode("=", $cursor );
if (isset($explode[0]) && $explode[0] != ''){
$final_result[trim($explode[0])] =array (trim($explode[1]),trim($explode[2])) ;
}
}
var_dump($final_result);
The result is:
array(3) {
'Test' =>
array(2) {
[0] =>
string(8) "10849831"
[1] =>
string(15) "August 6, 2013:"
}
'56cake' =>
array(2) {
[0] =>
string(1) "0"
[1] =>
string(15) "August 6, 2013:"
}
'Wwe' =>
array(2) {
[0] =>
string(9) "812986192"
[1] =>
string(15) "August 6, 2013:"
}
}