Convert PHP String to Associative Array - php

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);
}
}

Related

Reading from a file into an associative array

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"
}
}
}

Php array value to keys

Hi let's say I have this array
array(2) {
[0]=>
string(9) "name|a-z+"
[1]=>
string(7) "id|0-9+"
}
Now I want a new array (or the same if possible) to be like this:
array(2) {
[name]=>
string(4) "a-z+"
[id]=>
string(4) "0-9+"
}
I think the solution implies explode and array_combine, but I am not good enough, can someone help me?
Thanks in advance.
function convert_my_array($arr){
$out = array();
foreach($arr as $obj){
$data = explode("|", $obj);
$out[$data[0]] = $data[1];
}
return $out;
}
Using the original array called $array here, loop through it set the values to what you want.
$newarray = array();
foreach ($array as $key=>$val) {
list($one, $two) = explode('|', $val);
$newarray[$one] = $two;
}

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)"

Create string to put in an IN statement from an array of arrays

I have an array of arrays that look like this:
array(40) {
[0]=>
array(2) {
["id"]=>
string(2) "ta"
["size"]=>
int(2)
[1]=>
array(2) {
["id"]=>
string(2) "tq"
["size"]=>
int(4)
....
I want to be able to get all the sizes in a way that I can do a query like this:
IN (2,4)
so... For each array, get the size key: IN (size,size,size...)
Thanks!
You could do something like this:-
$sizes = implode(',', array_map(function($v) { return $v['size']; }, $array));
Then just pass $sizes to your IN query
edit
In response to your comment below, you can use array_unique to remove duplicate sizes, eg:
$sizes = implode(',', array_unique(array_map(function($v) { return $v['size']; }, $array)));
Here you go:
$a = array("id"=>"ta","size"=>2);
$b = array("id"=>"tq","size"=>4);
$c = array($a,$b);
$in = array();
foreach ($c as $key=>$value) {
if(array_key_exists("size", $value)){
$in[] = $value["size"];
}
}
echo implode(",", $in);
$sizes = array();
foreach($array as $value) {
$sizes[] = $value['size'];
}
$query = implode(',', $sizes);
query ..." IN ($query) "..

How to search array item with given string

i have an array:
$mainArr = ["SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS"];
$strArr = ["SRI"];
i want to search the main Array with the given string Array element so that if the string is matched it should get the corresponding key,value pair.
expected o/p would be:
Array[
0->SRI
3->SRI#AIS
4->SRI#GOW
5->SRI#AIS#GOW
]
Any ideas ?
Thanks,
Srinivas
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");
$strArr = array("SRI");
foreach ($mainArr as $key => $value)
{
foreach ($strArr as $str)
{
if (strpos($value,$str) !== false) $rez[$key] = $value;
}
}
var_dump($rez);
output:
array(4) {
[0]=> string(3) "SRI"
[3]=> string(7) "SRI#AIS"
[4]=> string(7) "SRI#GOW"
[5]=> string(11) "SRI#GOW#AIS"
}
I thing i ll help u,,
$test=array();
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");
$strArr = array("SRI");
foreach ($mainArr as $key => $value)
{
$temp = explode('#',$value);
//$temp = $temp[0];
if(in_array($temp[0],$strArr))
$test[$key]=$value;
}
echo "<pre><span style='color:black; font-size:19;'>";print_r($test);echo "</span></pre>";
Use array_filter:
function filter($element)
{
return strpos($element, 'SRI') !== false;
}
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");
$filteredArr = array_filter($mainArr, 'filter');

Categories