Explode string with two different separators to create multidimensional array - php

I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!

Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.

It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507

you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!

There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));

Related

From CSV to array with headerkeys, now back to CSV

Our Story: (short version below if you're eager to troubleshoot)
This question is asked after extensively searching for a way to get a multidimensional array (with named keys) back into it's CSV file. You might say: "But this is covered on multiple pages on SO, search better!" but we did, and the results we found we have tried to bend to our will, but failed.
The reason for this in the first place was to remove columns from the CSV that were interfering with the rest of our Query's and Code.
So now we're back to ask on SO:
We've read the CSV into a multidimensional Array, using the headers' 1st line as key names.
We then used unset($array[$i]['insert_date']); to remove the columns from the array
We also str_replace'd those columns names from our $header variable.
So we're extensively reading out csv's, putting them in awesome Arrays that have a numerical first index, and second dimension keys named after the first line of our CSV file.
We also have the original Header from CSV file stored in a variable handsomely called $header with a string like: '"brand";"category";"category_path"
So.. $header is a string, $array is our multidimensional array.
All we want to do, and we're stuck editing loop after loop, is to create a brand new File, that has our $header as the first line, and our $array's values as strings..
file to write to: $putfile = fopen("feeds/broken/lu-zz.csv", "rw");
we're using: fputcsv($file, $array,';','"'); to write
and preferably: \n line endings
In short:
from this:
array (size=3886)
0 =>
array (size=19)
'brand' => string 'Tommy Hilfiger' (length=14)
'category' => string '' (length=0)
'category_path' => string 'Heren|Jeans|Blue jeans' (length=22)
1 =>
array (size=19)
'brand' => string 'Marc Aurel' (length=10)
'category' => string '' (length=0)
'category_path' => string 'Dames|Jurken|Zomerjurken' (length=24)
2 =>
array (size=19)
'brand' => string 'Rinascimento' (length=12)
'category' => string '' (length=0)
'category_path' => string 'Dames|Jurken|Print jurken' (length=25)
To This
"brand";"category";"category_path"
"Tommy Hilfiger";"";"Heren|Jeans|Blue jeans" (/n)
"Marc Aurel";"";"Dames|Jurken|Zomerjurken" (/n)
"Rinascimento";"";"Dames|Jurken|Print jurken" (/n)
Last piece of code we tried:
{
foreach($subarray as $value){
for ($i=0, $m=count($value); $i<$m; $i++){
//$test = implode('";"',$subarray) ;
//$tmp = array();
$result = call_user_func_array('array_merge', $subarray);
//$tmp[]= array_merge($subsub[$i]);
var_dump($result);
fputcsv($putfile, $subarray,';','"');
}
}
} fclose($putfile);
This just returns the same value over and over again into an array:
foreach ($array as $subarray) {
foreach($subarray as $value){
for ($i=0, $m=count($value); $i<$m; $i++){
//$test = implode('";"',$subarray) ;
//$tmp = array();
print_r($subarray);
fputcsv($putfile, $subarray,';','"');
}
}
} fclose($putfile);
Solution in our case: Thanks to "Don't Panic" & "CBroe".
$putfile = fopen("feeds/stukkefeeds/lu-zz.csv", "wb");
$header = str_replace('"','',$header1);
$titel = explode(';',$header);
var_dump($titel);
// then write in your data
fputcsv($putfile, $titel,';','"');
foreach ($array as $line) {
fputcsv($putfile, $line,';','"');
}
It looks like you may be making it more complicated than it needs to be. If you have an $array that is the one you've shown that looks like:
array (size=3886)
0 =>
array (size=19)
'brand' => string 'Tommy Hilfiger' (length=14)
'category' => string '' (length=0)
'category_path' => string 'Heren|Jeans|Blue jeans' (length=22)
...
And you have a working file handle that you've opened with
$putfile = fopen("feeds/broken/lu-zz.csv", "w");
You shouldn't need a nested loop at all. You can get the header line by using array_keys on the first item in the array (or any item, really), write it to the file with fputcsv, and then loop over the array and write each line of data, also with fputcsv.
$first_line = reset($array); // get the first line
fputcsv($putfile, array_keys($first_line)); // use its keys to write the headers
// then write in your data
foreach ($array as $line) {
fputcsv($putfile, $line,';','"');
}
Looks like you are thinking way too complicated here ...
$firstIteration = true;
foreach($yourArray as $elem) {
if($firstIteration ) { // if this is the first array element,
// write out its keys to create the CSV heading line
echo implode(';', array_keys($elem)) .'<br>';
$firstIteration = false;
}
echo implode(';', $elem) .'<br>'; // output the data for each array element
}
(Notice that I used echo and implode here for demonstration purposes; the result will not have the enclosing " - switching that out for writing CSV to the file again should be no issue.)

json_decode - Force array keys to be string

Take a look at the following code:
$a = json_decode('{"0":"xy"}', true);
This will return an associative array like [0 => "xy"].
Is there a way not to automatically convert the keys to numbers? The result I'd like to have would be the array ["0" => "xy"] with strings as keys exclusively.
First decode it as an object (without true parameter) and then typecast it as array:
$a = (array) json_decode('{"0":"xy"}');
var_dump($a);
Ouput:
array (size=1)
'0' => string 'xy' (length=2)
Not really sure why you would want numerical array keys to be strings. It can make life harder when trying to search through an array by key or rekey the array.
However, if you really want your keys to be strings this should help
$array = json_decode('{"0":"xy"}', true);
foreach($array as $key => $value) {
$newArray[(string) $key] = $value;
}

Create php array from strings that contains bracket literals

I have a number of strings, that contain the bracket literals:
0 => string '[139432,97]' (length=18)
1 => string '[139440,99]' (length=18)
I need to create string arrays of [139432,97] and [139440,99].
I've tried using json_decode(), but while it works, it creates arrays as float or int using the above data, however I want them as strings.
array (size=2)
0 => float 139432
1 => int 97
array (size=2)
0 => float 139440
1 => int 97
You can put double quotes around the values e.g.
0 => string '["139432","97"]' (length=22)
1 => string '["139440","99"]' (length=22)
This way when you json_decode they should be strings.
Edit:
OK I thought you could control the input - if not then a simple trim and explode could do:
explode(',', trim('[139432,97]', '[]'));
array(2) {
[0]=>
string(6) "139432"
[1]=>
string(2) "97"
}
Is that enough?
Just combining what you already now (json_decode) and what #AlixAxel suggested here you can extract those values to string link:
$subject = '[139432,97]';
$convertedToArrayOfStrings = array_map('strval', json_decode($subject));
or
$convertedToArrayOfString = array_map(function($item){return (string) $item;}, json_decode($subject));
for better performance, see the comment bellow please :)
Why not try with loop and use explode function:
$array = array('139432,97', '139440,99');
$finalArray = array();
$i = 0;
foreach ($array as $arr) {
$explode = explode(",", $arr);
$j = 0;
foreach ($explode as $exp) {
$finalArray[$i][$j] = (int)$exp;
$j++;
}
$i++;
}

How to get next value in a multidimensional array

I am trying to produce a HTML list grouped by "groupName" from the array below.
array (size=30)
0 =>
array (size=4)
'groupOrder' => string '1' (length=1)
'groupName' => string 'Class' (length=11)
'txt' => string '............' (length=32)
'ID' => string '6' (length=1)
1 =>
array (size=4)
'groupOrder' => string '1' (length=1)
'groupName' => string 'Size' (length=11)
'txt' => string '..................' (length=34)
'ID' => string '6' (length=1)
2 =>
...
So I'd like produce something like this pseudo list:
groupName
txt
txt
txt
next GroupName
txt
txt
...
So my code looks like this
foreach ($datafeed as $val => $row) {
if (($datafeed[$val]['groupName']) == next($datafeed[$val]['groupName'])) {
//same group - do nothing
} else {
echo $datafeed[$val]['groupName'];
}
echo "<li>".$row['txt']. "</li>";
}
But I'm getting errors about "next() expects parameter 1 to be array, string given".
I've tried all sorts of different syntax, but I'm not making much progress. How do I compare two values in a nested array?
You misinterpreted the meaning of the function next(): you cannot query it for an array element. It manipulates the internal array pointer tied with the array itself, not with some its element. From the PHP documentation:
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
and see also a description of next.
Since the foreach loop crucially depends on the value of the array pointer, messing with the array pointer will ruin the loop: you probably see every second element in the loop, because at every iteration once next() is called by your foreach loop and then once by yourself.
The simplest thing for you is probably to use the old good for loop:
for ($i = 0; $i < length ($array); $i++)
{
if ($i == 0 || $array[$i] != $array[$i - 1])
echo "New group!\n";
echo $array[$i];
}
This doesn't answer your question directly, but you'd be better off restructuring your array so that they're grouped, and you don't need to perform any logic within the loop to check the groupName. Currently, you're relying on the next groupName to match the current groupName, but if they're not sequential, they won't be grouped.
You could do something like this:
$output = array();
foreach ($datafeed as $feed) {
$output[$feed['groupName']][] = $feed;
}
Here's a demo
You should not use next inside a foreach loop anyway, since you'll get conflicting array pointer movements. Simply store the last value:
$last = null;
foreach (...) {
if ($last != $row['current']) {
// new group
}
$last = $row['current'];
...
}

How to split an array by every nth appearance of a string?

This question is different to Split, a string, at every nth position, with PHP, in that I want to split a string like the following:
foo|foo|foo|foo|foo|foo
Into this (every 2nd |):
array (3) {
0 => 'foo|foo',
1 => 'foo|foo',
2 => 'foo|foo'
}
So, basically, I want a function similar to explode() (I really doubt that what I'm asking will be built-in), but which 'explodes' at every nth appearance of a certain string.
How is this possible?
You can use explode + array_chunk + array_map + implode
$string = "foo|foo|foo|foo|foo|foo";
$array = stringSplit($string,"|",2);
var_dump($array);
Output
array
0 => string 'foo|foo' (length=7)
1 => string 'foo|foo' (length=7)
2 => string 'foo|foo' (length=7)
Function used
function stringSplit($string, $search, $chunck) {
return array_map(function($var)use($search){return implode($search, $var); },array_chunk(explode($search, $string),$chunck));
}

Categories