Reading from a file into an associative array - php

I have to create a page, where the user is able to search a suburb and the page will print the postcode of that suburb.
I am having a little difficulty with putting the data from the .txt document into the variables for the associative array.
Thanks for your help.
This is what I have so far.
<?php
$file = "postcode.txt";
$handle = fopen($file, 'r');
$postcodearray = file($file);
$suburb = explode(",", );
$postcodearray[$suburb] = $postcode;
fclose($handle)
?>
and this is the format of the .txt document...
3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
etc.

$postcodearray = file($file);
foreach($postcodearray as $pca){
$p_codes=explode(',',$pca);
$postcodearray2[$p_codes[1]] = $p_codes[0];
}
print_r($postcodearray2);

I prefer file_get_contents when working with files
<?php
$content = file_get_contents('postcode.txt');
$rows = explode("\n", $content);
$data = [];
foreach ($rows as $row) {
$columns = explode(',', $row);
$data[$columns[0]] = $columns[1];
}

An alternative array would group MELBOURNE EAST and WEST in one array with subarrays. (Look at the output, I don't know how to explain it)
I explode MELBOURNE EAST on space and use EAST as a key in the array.
// Replace this line with file_get_contents("postcode.txt");
$txt = "3000,MELBOURNE
3001,MELBOURNE
3002,EAST MELBOURNE
3003,WEST MELBOURNE
3603,WEST SYDNEY
3103,NORTH PERTH";
$rows = explode(PHP_EOL, $txt);
$arr= [];
foreach($rows as $row){
List($postcode, $suburb) = explode(",", $row);
If(in_array(substr($suburb,0,4), array("EAST", "WEST")) || in_array(substr($suburb,0,5), array("SOUTH", "NORTH"))){
// If the suburb includes a direction explode it to temp.
$temp = explode(" ", $suburb);
$arr[$temp[1]][$temp[0]][] = $postcode;
}else{
// If there is no direction just save it as suburb "main"
$arr[$suburb][] = $postcode;
}
}
Var_dump($arr);
https://3v4l.org/RXgSR
Output:
array(3) {
["MELBOURNE"]=>
array(4) {
[0]=>
string(4) "3000"
[1]=>
string(4) "3001"
["EAST"]=>
array(1) {
[0]=>
string(4) "3002"
}
["WEST"]=>
array(1) {
[0]=>
string(4) "3003"
}
}
["SYDNEY"]=>
array(1) {
["WEST"]=>
array(1) {
[0]=>
string(4) "3603"
}
}
["PERTH"]=>
array(1) {
["NORTH"]=>
array(1) {
[0]=>
string(4) "3103"
}
}
}

Related

Convert PHP String to Associative Array

I have a string that looks like the below:
Name,Age,Location
Jo,28,London
How would I convert this into an associative array so it reads like this:
Array
(
[Name] => Jo
[Age] => 28
[Location] => London
)
I've tried to explode the string and manipulate it that way but got nowhere fast ($body = explode(',', $body);) I tried to use array_map() but it expected an array in the first place.
I've looked through a few articles (PHP CSV to Associative Array with Row Headings) but again they are using array_map().
You are trying to over-engineer simple thing, which result in wasting too much time for having task done.
$str = "Name,Age,Location\nJo,28,London";
$lines = explode("\n", $str);
$keys = explode(',', $lines[0]);
$vals = explode(',', $lines[1]);
$result = array_combine($keys, $vals);
But even ordinary loop would do the trick in your case and this is what you should end up with unless you had better ideas:
$result = [];
for($i=0; $i<count($keys); $i++) {
$result[$keys[$i]] = $vals[$i];
}
I also recommend getting thru list of available built-in array functions for future benefits.
This answer will handle multilined CSV files.
Array_shift will take the first line and make that the keys, then loop the rest of the lines and use the keys in array_combine.
$str = "Name,Age,Location
Jo,28,London
Do,35,London";
$arr= explode("\n", $str);
$keys = explode(",",array_shift($arr));
foreach($arr as $line){
$new[]= array_combine($keys, explode(",", $line));
}
var_dump($new);
https://3v4l.org/hAmCN
array(2) {
[0]=>
array(3) {
["Name"]=>
string(2) "Jo"
["Age"]=>
string(2) "28"
["Location"]=>
string(6) "London"
}
[1]=>
array(3) {
["Name"]=>
string(2) "Do"
["Age"]=>
string(2) "35"
["Location"]=>
string(6) "London"
}
}
you try this code:
$ex = explode(PHP_EOL, $string)
$arr = array_combine(explode(',',$ex[0]), explode(',',$ex[1]));
print_r($arr);die;
Try this, it's working:
$content = $string;
$delimiter = ",";
$enclosure = '"';
$escape = "\\" ;
$rows = array_filter(explode(PHP_EOL, $content));
$header = NULL;
$data = [];
foreach($rows as $row)
{
$row = str_getcsv ($row, $delimiter, $enclosure , $escape);
if(!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}

how to format a json file?

I am new to JSON and I am wondering how i could format my JSON file so I will be able to render it in a barchart.
I've got the following PHP code:
<?php
$search_value=$_POST["search"];
$mysqli = new mysqli('localhost','root','password','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray = $row;
}
file_put_contents('jsonoutput.json', json_encode($myArray));
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
?>
My actual output:
(given a gene (xkr4) as input)
{"genename":"xkr4","TA11MEAN":"974.25","TA11STD":"99.0085223605","TA21MEAN":"710.75","TA21STD":"115.79831605","TA22MEAN":"736.5","TA22STD":"115.79831605","TA23MEAN":"903.75","TA23STD":"107.283211641","TB11MEAN":"799.25","TB11STD":"97.2660655111","TB21MEAN":"658","TB21STD":"91.7959694104","TB22MEAN":"592.75","TB22STD":"70.9379129944","TB23MEAN":"864","TB23STD":"92.7280971443"}
How I'd like to get my output:
{"genename":"xkr4",{"TA11MEAN":"974.25"},{"TA11STD":"99.0085223605"},{"TA21MEAN":"710.75"},{"TA21STD":"115.79831605"},{"TA22MEAN":"736.5"},{"TA22STD":"115.79831605"},{"TA23MEAN":"903.75"},{"TA23STD":"107.283211641"},{"TB11MEAN":"799.25"},{"TB11STD":"97.2660655111"},{"TB21MEAN":"658"},{"TB21STD":"91.7959694104"},{"TB22MEAN":"592.75"},{"TB22STD":"70.9379129944"},{"TB23MEAN":"864"},{"TB23STD":"92.7280971443"}}
If someone could give me direction on this (or solve it) That would be great!
Thanks in advance :)
I would suggest you to first check how are you getting back your data in array.
$myArray[] should have the data populated as shown below. Then use JSON_PRETTY_PRINT.
/*USED TO SHOW FULL ARRAY SIZE*/
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
$myArray=array("genename"=>array(array("xkr4"=>array(
array("TA11MEAN"=>"974.25","TA11STD"=>"99.0085223605"),
array("TA21MEAN"=>"710.75","TA21STD"=>"115.79831605"),
array("TA22MEAN"=>"736.5","TA22STD"=>"115.79831605"),
array("TA23MEAN"=>"903.75","TA23STD"=>"107.283211641"),
array("TB11MEAN"=>"799.25","TB11STD"=>"97.2660655111"),
array("TB21MEAN"=>"658","TB21STD"=>"91.7959694104"),
array("TB22MEAN"=>"592.75","TB22STD"=>"70.9379129944"),
array("TB23MEAN"=>"864","TB23STD"=>"92.7280971443"),
))));
$jsonData=json_encode($myArray,JSON_PRETTY_PRINT);
var_dump($jsonData);
$json_from_database='[{"genename":"xkr4","TA11MEAN":"974.25","TA11STD":"99.0085223605","TA21MEAN":"710.75","TA21STD":"115.79831605","TA22MEAN":"736.5","TA22STD":"115.79831605","TA23MEAN":"903.75","TA23STD":"107.283211641","TB11MEAN":"799.25","TB11STD":"97.2660655111","TB21MEAN":"658","TB21STD":"91.7959694104","TB22MEAN":"592.75","TB22STD":"70.9379129944","TB23MEAN":"864","TB23STD":"92.7280971443"}]';
//print decode array from databse
$decoded=json_decode($json_from_database);
var_dump($decoded);
foreach ($decoded[0] as $key => $value) {
echo "\n ";
print $key;
print " " .$decoded[0]->$key;
}
array(1) {
[0]=>
object(stdClass)#1 (17) {
["genename"]=>
string(4) "xkr4"
["TA11MEAN"]=>
string(6) "974.25"
["TA11STD"]=>
string(13) "99.0085223605"
["TA21MEAN"]=>
string(6) "710.75"
["TA21STD"]=>
string(12) "115.79831605"
["TA22MEAN"]=>
string(5) "736.5"
["TA22STD"]=>
string(12) "115.79831605"
["TA23MEAN"]=>
string(6) "903.75"
["TA23STD"]=>
string(13) "107.283211641"
["TB11MEAN"]=>
string(6) "799.25"
["TB11STD"]=>
string(13) "97.2660655111"
["TB21MEAN"]=>
string(3) "658"
["TB21STD"]=>
string(13) "91.7959694104"
["TB22MEAN"]=>
string(6) "592.75"
["TB22STD"]=>
string(13) "70.9379129944"
["TB23MEAN"]=>
string(3) "864"
["TB23STD"]=>
string(13) "92.7280971443"
}
}
genename xkr4
TA11MEAN 974.25
TA11STD 99.0085223605
TA21MEAN 710.75
TA21STD 115.79831605
TA22MEAN 736.5
TA22STD 115.79831605
TA23MEAN 903.75
TA23STD 107.283211641
TB11MEAN 799.25
TB11STD 97.2660655111
TB21MEAN 658
TB21STD 91.7959694104
TB22MEAN 592.75
TB22STD 70.9379129944
TB23MEAN 864
TB23STD 92.7280971443
This is how your data looks like from database it is a array of rows row is a object
I solved it:
<?php
$search_value=$_POST["search"];
$mysqli = new mysqli('localhost','root','password','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray = $row;
}
//file_put_contents('jsonoutput.json', json_encode($myArray));
$json = json_encode($myArray);
$array = json_decode($json, true);
$new_array = array();
foreach( $array as $key => $value ){
$newarray[] = array($key=>$value);
}
echo json_encode($newarray);
file_put_contents('jsonoutput.json', json_encode($newarray));
}
$result->close();
$mysqli->close();
?>

How to return specific data from json_decode

I'm accessing data from an API using json_decode. The code I have returns the array of ALL the date (see below), but I want to return specific data such as 'name' or 'locale'.
$json_string = 'http://api.duedil.com/open/search?q=Surfing%20Sumo&api_key=THE-API-KEY';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo '<pre>';
var_dump($obj);
This is what is returned (this is abbreviated to save space here):
array(1) {
["response"]=>
array(2) {
["pagination"]=>
string(79) "http://api.duedil.com/open/search?query=Duedil&total_results=6&limit=5&offset=5"
["data"]=>
array(5) {
[0]=>
array(4) {
["company_number"]=>
string(8) "06999618"
["locale"]=>
string(14) "United Kingdom"
["name"]=>
string(14) "Duedil Limited"
["uri"]=>
string(51) "http://api.duedil.com/open/uk/company/06999618.json"
}
You could just use
$name = $obj['response']['data'][0]['name'];
$locale = $obj['response']['data'][0]['locale'];
if you have multiple return values, you could loop over them
foreach ($obj['response']['data'] as $item) {
$name = $item['name'];
$locale = $item['locale'];
}
try this sample code:
<?php
$data = isset($obj['response']['data'])?$obj['response']['data']:FALSE;
if(is_array($data))
{
foreach ($data as $value) {
echo $value['name'];
echo $value['locale'];
}
}

php arrays to CSV

I have an array of arrays
$numbers= array(3) {
[months]=>
array(3) {
["1"]=>
string(7) "Jan"
["2"]=>
string(7) "Feb"
["3"]=>
string(7) "Mar"
}
[dates]=>
array(3) {
["1"]=>
string(7) "12th"
["2"]=>
string(7) "19th"
["3"]=>
string(7) "22nd"
}
[people]=>
array(3) {
["1"]=>
string(7) "Bill"
["2"]=>
string(7) "Ted"
["3"]=>
string(7) "Gary"
}
}
I want to write the contents of these arrays into a CSV file in the form of a table
so I get an output like:
months, dates, people
Jan, 12th, Bill
Feb, 19th, Ted
Mar, 22nd, Gary
I want to try and put it directly from the array into the CSV in one move it it's possible but I can't find a way to do it without cutting it up.
<?php
// transform the array
$keys = array_keys($numbers);
array_unshift($numbers, null);
$output = call_user_func_array('array_map', $numbers);
array_unshift($output, $keys);
// from php.net
$fp = fopen('file.csv', 'w');
foreach ($output as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
$mi = new MultipleIterator();
$headers = array();
foreach($numbers as $header => $data) {
$mi->attachIterator(new ArrayIterator($data));
$headers[] = $header;
}
$fh = fopen('myfile.csv', 'w');
fputcsv($fh, $headers);
foreach($mi as $values) {
fputcsv($fh, $values);
}
fclose($fh);

split a comma separated string in a pair of 2 using php

I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.
You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.
<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"

Categories