Reading text file into an array - php

I am looking to convert a text based DAT file into an array in PHP. Normally I would be able to read each line and explode it into an array but this file is different.
[0]
FirstRideOn=43169.5701090972
Laps=4591
LastRideOn=43224.7924173611
Name=Standard 1
Nr=1
ResetDate=0
RunningTime=2481
Runs=233
TranNr=7435191
[1]
FirstRideOn=43149.5406271644
Laps=5528
LastRideOn=43224.7616565972
Name=Standard 2
Nr=2
ResetDate=0
RunningTime=2957
Runs=292
TranNr=8377256
I was hoping to load it into an associative array.
Any feedback or suggestions are greatly appreciated!

It's not clear from your question exactly what format you want the array to be in. So here are two alternatives. First we read the file into an array:
$input= file('somefile.dat', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
Then we can process the array to make an associative array. Here's the first option:
$output = array();
foreach ($input as $line) {
if (preg_match('/^\[(\d+)\]$/', $line, $matches)) {
$entry = (int)$matches[1];
$output[$entry] = array();
}
else {
list($key, $value) = explode('=', $line);
$output[$entry][$key] = $value;
}
}
print_r($output);
Which generates this output:
Array
(
[0] => Array
(
[FirstRideOn] => 43169.5701090972
[Laps] => 4591
[LastRideOn] => 43224.7924173611
[Name] => Standard 1
[Nr] => 1
[ResetDate] => 0
[RunningTime] => 2481
[Runs] => 233
[TranNr] => 7435191
)
[1] => Array
(
[FirstRideOn] => 43149.5406271644
[Laps] => 5528
[LastRideOn] => 43224.7616565972
[Name] => Standard 2
[Nr] => 2
[ResetDate] => 0
[RunningTime] => 2957
[Runs] => 292
[TranNr] => 8377256
)
)
Or we can do it this way:
// alternate style
$output = array();
foreach ($input as $line) {
if (preg_match('/^\[(\d+)\]$/', $line, $matches)) {
$entry = (int)$matches[1];
}
else {
list($key, $value) = explode('=', $line);
if (!array_key_exists($key, $output)) $output[$key] = array();
$output[$key][$entry] = $value;
}
}
print_r($output);
which generates this output. The choice is yours!
Array
(
[FirstRideOn] => Array
(
[0] => 43169.5701090972
[1] => 43149.5406271644
)
[Laps] => Array
(
[0] => 4591
[1] => 5528
)
[LastRideOn] => Array
(
[0] => 43224.7924173611
[1] => 43224.7616565972
)
[Name] => Array
(
[0] => Standard 1
[1] => Standard 2
)
[Nr] => Array
(
[0] => 1
[1] => 2
)
[ResetDate] => Array
(
[0] => 0
[1] => 0
)
[RunningTime] => Array
(
[0] => 2481
[1] => 2957
)
[Runs] => Array
(
[0] => 233
[1] => 292
)
[TranNr] => Array
(
[0] => 7435191
[1] => 8377256
)
)

Related

PHP array_keys multiple levels

I have array1 like this:
Array
(
[0] => 123
[1] => 456
[2] => 789
)
And array 2 like this
Array
(
[0] => Array
(
[0] => some text
[1] => 888
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[2] => Array
(
[0] => some text
[1] => 999
[2] => some
[3] => text
)
[3] => Array
(
[0] => some text
[1] => Array
(
[1] => 456
[2] => 789
)
[2] => some
[3] => text
)
[4] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
I am checking only 1. column of second array and finding values that match values from first array. This is my code:
$test=array();
$xcol = array_column($array2, 1);
foreach( $array1 as $key => $value ) {
if( ($foundKey = array_keys($xcol, $value)) !== false ) {
$rrt=$foundKey;
foreach($rrt as $rte){
$test[]=$array2[$rte];
}
}
}
echo "<pre>";
print_r($test);
echo "</pre>";
It is working and giving me proper results but it does not check for all levels. Can anybody please point me what am I doing wrong?
My output is:
Array
(
[0] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
And desired output is:
Array
(
[0] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
[1] => Array
(
[0] => some text
[1] => Array
(
[1] => 456
[2] => 789
)
[2] => some
[3] => text
)
[2] => Array
(
[0] => some text
[1] => 123
[2] => some
[3] => text
)
)
Solution:
create a loop which loop your $array2 which holds datas you wanted to get whos values match in first array $array1
foreach($array2 as $data) {
Inside loop create another loop which loop your indexes
foreach($data as $value) {
But before than create a condition if your index value is array loop it and check it it's index value is match in any indexes from $array1 use php function in_array for that
if (gettype($value) == "array") {
foreach($value as $val) {
if (in_array($val, $array1) ) {
$result[] = $data;
Then if you find it just stop the loop using break to avoid duplication
break;
}
}
Else you just directly use in_array
} else if (in_array($value, $array1)) {
$result[] = $data;
}
}
}
Just grab the code here in Demo
Help it helps just mark it answer if you are satisfied to it
Lets make a recursive method for this. What is recursion you ask? Well it is simply a method that calls it self.
<?php
$array1 = array(123,456,789);
$array2 = array(
array(
"some text"
, 888
, "some"
, "text"
),
array(
"some text"
,123
,"some"
,"text"
),
array(
"some text"
,999
,"some"
,"text"
),
array(
"some text"
,array(456,789)
,"some"
,"text"
),
array(
"another text"
,123
,"some"
,"text"
)
);
$final = array();
foreach($array1 as $needle){
foreach($array2 as $haystack){
if(find($needle,$haystack)){
$final[] = $haystack;
}
}
}
print_r($final);
function find($needle, $haystack){
$result = false;
foreach ($haystack as $value) {
if(is_array($value)){
$result = find($needle, $value);
} else {
if($needle == $value){
$result = true;
}
}
}
return $result;
}

PHP convert json into csv with sub array

I was creating php code to convert the below json to csv
Array
(
[data] => Array
(
[0] => Array
(
[DESC] => bla bal bal
[SOLD] => 0
[contact_no] => 1234
[title] => Hiiiii
[price] => 10900
[big_image] => Array
(
[0] => http://example.com/images/user_adv/14.jpg
[1] => http://example.com/images/user_adv/15.jpg
)
[small_image] => Array
(
[0] => http://example.com/images/user_adv/small/14.jpg
[1] => http://example.com/images/user_adv/small/15.jpg
)
[tpe] => user
)
[1] => Array
(
[DESC] => fo fo fof ofof
[SOLD] => 0
[contact_no] => 234522
[title] => Hellooooo sddf
[price] => 0
[big_image] => Array
(
[0] => http://example.com/images/user_adv/154.jpg
[1] => http://example.com/images/user_adv/144.jpg
[2] => http://example.com/images/user_adv/147.jpg
)
[small_image] => Array
(
[0] => http://example.com/images/user_adv/small/154.jpg
[1] => http://example.com/images/user_adv/small/144.jpg
[2] => http://example.com/images/user_adv/small/147.jpg
)
[tpe] => user
)
)
[pis] => 3
[totals] => 23
[curpage] => 1
[total_ads] => 71
)
I've been using the below code to export it to .csv
$fp = fopen("output.csv","w");
foreach ($json['data'] as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
I can convert it fine, but I face a small issue that the sub array which is big_image & small_image is NOT appearing in the output file .csv (the row is empty)
[big_image] => Array
(
[0] => http://example.com/images/user_adv/154.jpg
[1] => http://example.com/images/user_adv/144.jpg
[2] => http://example.com/images/user_adv/147.jpg
)
[small_image] => Array
(
[0] => http://example.com/images/user_adv/small/154.jpg
[1] => http://example.com/images/user_adv/small/144.jpg
[2] => http://example.com/images/user_adv/small/147.jpg
)
By the way, if I replace:
foreach ($json['data'] as $fields) {
with
foreach ($json['data'][0] as $fields) {
I get the link pictures as output, so I need to merge them as one output
foreach ($json['data'] as $fields) {
foreach ($json['data'][0] as $fields2) {
edit :
here the output
edit 2 :
i expect the output something like that
You could make a function to make sure those nested arrays are made flat. You can create a utility function for that, like this:
function array_flatten ($nonFlat) {
$flat = array();
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($nonFlat)) as $k=>$v) {
$flat[$k] = $v;
}
return $flat;
}
And call it like this:
$fp = fopen("output.csv","w");
foreach ($json['data'] as $fields) {
fputcsv($fp, array_flatten($fields));
}
fclose($fp);

How to parse this simple text-block into a multi-dimensional array, in PHP?

I have a simple text-block; and, its content is:
txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).
And, there is already an simple array, in PHP code:
$my_array = array();
Now, I want to parse into this PHP array, like:
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
All data is general. Could you help me to do it, with PHP?
<?php
// Initially put your input into a variable
$txt=<<<__EOT__
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
__EOT__;
$result = array();
// separate out each row
$rows = explode("\n", $txt);
// loop through each row
foreach($rows as $row) {
// Use a regular expression to find the key and values
$success = preg_match('/^([^(]+)\(([^)]+)\)\.$/', $row, $parts);
// Check the regexp worked
if(!$success) {
echo 'Failed to match row: ' . $row . "\n";
continue;
}
// get the array key from the regexp results
$key = $parts[1];
// the values are all a string, split on the comma to make an array
$values = explode(',', $parts[2]);
// store $key and $values in the result
$result[$key] = $values;
}
// See if it worked
var_dump($result);
Suppose this answer will help you
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_3(val_a,val_b,val_c).
";
$myArry = explode(".", $text);
$resArry = array();
foreach ($myArry as $key => $value) {
if(trim($value)!=""){
$plain = str_replace(array("(",")"),",",$value);
$subArry = explode(",",$plain);
$keyN = explode("(",trim($value));
unset($subArry[array_search($keyN[0],$subArry)]);
unset($subArry[array_search("",$subArry)]);
$resArry[$keyN[0]][]=$subArry;
}
}
echo "<pre/>";
print_r($resArry);
die;
//Output will be like
Array
(
[txt_1] => Array
(
[0] => Array
(
[1] => val_1
[2] => val_2
[3] => val_3
)
)
[txt_2] => Array
(
[0] => Array
(
[1] => val_4
[2] => val_5
[3] => val_6
)
)
[txt_3] => Array
(
[0] => Array
(
[1] => val_a
[2] => val_b
[3] => val_c
)
)
)
$input = 'txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).'; // the input string
$temp = explode('.', $input); // seprates from .
$temp = array_filter($temp); // for cutting blank values
$temp = array_map('trim', $temp); // removes newlines
$final = [];
foreach($temp as $val)
{
$key = strtok($val, '('); // search upto token (
$final[$key][] = explode(',' ,strtok(')')); // advance token to )
}
unset($val, $temp); // unset non required things
Here is the output for $final,
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
Test it here: http://phptester.net/
NOTE: In order to use the short array syntax [] use PHP 5.4
<?php
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
";
$myArray = [];
//You're gonna see why we want to remove this character
//later, it will help us have a cleaner code.
$text = str_replace(')', '', $text);
$arrayGroup = explode('.', $text);
//print_r($arrayGroup);
foreach($arrayGroup as $array) {
$exp = explode('(', $array);
$arrayName = trim($exp[0]);
$arrayValues = explode(',', $exp[1]);
foreach($arrayValues as $value) {
${$arrayName}[] = $value;
}
$myArray[$arrayName] = $$arrayName;
}
echo '<pre>';
print_r($myArray);
echo '</pre>';
echo '<pre>';
print_r($myArray['txt_2']);
echo '</pre>';
After all this, you can use the txt_1 or txt_2 or whatever later, because the variables were created dynamically.
Later in the code you can use $myVar = txt_1[3]; with no problem

how to get array from get to normal array in php

I have an array like this and it can contain multiple values:
Array
(
[rpiid] => Array
(
[1] => 86
)
[sensor_id] => Array
(
[1] => 1
)
[when] => Array
(
[1] => 2014-02-24
)
[val] => Array
(
[1] => 000
)
[train] => Array
(
[1] => True
)
[valid] => Array
(
[1] => False
)
[button] => update
)
Of course, here there is only the number 1 each time but sometimes I have 0, 1, 2 and a value associated. This is because I get this from a GET from multiple forms.
How can I transform this array into
Array
(
[0] => Array
(
[rpiid] => 86
[sensor_id] => 1
...
Thanks,
John.
if your array is $get
$newArray = Array();
foreach($get as $secondKey => $innerArray){
foreach($value as $topKey => $value) {
$newArray[$topKey][$secondKey] = $value;
}
}
This should work
$new_array = array();
foreach($first_array as $value => $key){
$new_array[$key] = $value[1];
}
Sure you can, take a look at this small example:
$a = [ 'rpid' => [1], 'cpid' => [2,2] ];
$nodes = [];
foreach($a as $node => $array) {
foreach($array as $index => $value) {
if(empty($nodes[$index]))
$nodes[$index] = [];
$nodes[$index][$node] = $value;
}
}
print_r($nodes):
Array
(
[0] => Array
(
[rpid] => 1
[cpid] => 2
)
[1] => Array
(
[cpid] => 2
)
)

PHP fetch 3d array

I have below array and i want to fetch [2] => Array with foreach but it's showing me an error.
for example array name is $other
Array
(
[0] => Array
(
[0] => aaaaaaaaaaaa
[1] => bbbbbbbbbbbb
[2] => cccccccccccc
)
[1] => Array
(
[0] => dddddddddddd
[1] => eeeeeeeeeeee
[2] => ffffffffffff
)
[2] => Array
(
[0] => gggggggggggg
[1] => hhhhhhhhhhhh
[2] => iiiiiiiiiiii
)
)
fetch array:
foreach ($other[2] as $value) {
echo $value.'<br/>';
}
How do I print all the values of the second array?
You need to nest further more
foreach ($other as $arr)
{
foreach($arr as $k=>$v)
{
if($k==2)
{
echo $v.'<br/>';
}
}
}
OUTPUT :
cccccccccccc
ffffffffffff
iiiiiiiiiiii
Try Something like this,
<?php
$x = array
(
0 => array
(
0 => 'aaaaaaaaaaaa',
1 => 'bbbbbbbbbbbb',
2 => 'cccccccccccc'
),
1 => array
(
0 => 'dddddddddddd',
1 => 'eeeeeeeeeeee',
2 => 'ffffffffffff'
),
2 => array
(
0 => 'gggggggggggg',
1 => 'hhhhhhhhhhhh',
2 => 'iiiiiiiiiiii'
)
);
$count = count($x);
$w = $count - 1;
var_dump($x[$w]);
?>

Categories