build multidimensional array from string php - php

EDIT: Here is a portion of $preparedstring:
555555,Jones,Brian,NYC,1000,2011-10-21 00:00:00,Check,1542,0, ,Check, ,0, ,Check, ,; 6666666,Miler,Christopher,Chicago,1000,2011-10-26 00:00:00,Check,6406,0, ,Check, ,0, ,Check, ,;
I am trying to convert a HTML table to a multidimensional array. I have converted the table into a long string, each cell being delimited with a comma and each row being delimited with a semicolon.
I am not exactly sure how to build the multidimensional array from this string. This is what I have tried so far:
<?php
$outerARR = explode(";", $preparedstring);
$arr = array
(
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$innerarr[0]=>array
(
$innerarr[];
)
}
);
?>
this gives me a syntax error near the
$arr = array
(
opening parenthesis.

Your approach to solving the problem is sadly very wrong, though there are many solutions to your problem, I would use something like the below.
How does the code work?
First we use explode to split our string up in smaller chunks, ; is our delimiter.
We pass this newly created array to array_map as it's second parameter.
array_map takes two parameters, the first one is a function that will be called for every member of the second paramater (which should be an array).
Inside our callback to array_map we use explode to once again split out the values, now with , as our delimiter.
$data = "1,2,3;4,5,6;7,8,9";
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $data)
);
print_r ($ret);
output
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
It doesn't work, why?
Probably because you are using a version of PHP prior to 5.3, if so you can use this snippet instead:
function explode_by_comma ($_) {
return explode (',', $_);
}
$ret = array_map ('explode_by_comma', explode (';', $data));

<?php
//explode first dimension of the array to create an array of rows
$outerARR = explode(";", $preparedstring);
$arr = array();
//iterate through the newly created array
foreach ($outerARR as $arrvalue) {
//explode this row into columns
$innerarr = explode(",", $arrvalue);
//add the newly created array of columns to the output array as a new index
$arr[] = $innerarr;
}
?>

You're close, but arrays don't work that way. You can't put a foreach inside an array constructor like that. It should look like this:
$outerARR = explode(";", $preparedstring);
$arr = array();
foreach ($outerARR as $arrvalue){
$innerarr = explode(",", $arrvalue);
$arr[] = $innerarr;
}
Demo: http://codepad.org/I5wFFczR

$outerARR = explode(";", $preparedstring);
$a = array();
$y=0;
foreach ($outerARR as $arrvalue){
$x=0;
$innerarr = explode(",", $arrvalue);
foreach($innerarr as $v){
$a[$y][$x++] = $v;
}
$y++;
}
print_r($a);
Array
(
[0] => Array
(
[0] => 555555
[1] => Jones
[2] => Brian
[3] => NYC
[4] => 1000
[5] => 2011-10-21 00:00:00
[6] => Check
[7] => 1542
[8] => 0
[9] =>
[10] => Check
[11] =>
[12] => 0
[13] =>
[14] => Check
[15] =>
[16] =>
)
[1] => Array
(
[0] => 6666666
[1] => Miler
[2] => Christopher
[3] => Chicago
[4] => 1000
[5] => 2011-10-26 00:00:00
[6] => Check
[7] => 6406
[8] => 0
[9] =>
[10] => Check
[11] =>
[12] => 0
[13] =>
[14] => Check
[15] =>
[16] =>
)
)

Related

How to add values to an array inside an array obtained through AJAX

In my PHP file, I'm receiving a total of 4 variables $data, $date, $shift and $val1.
$data is an array and the other 3 are date and 2 strings obtained through AJAX with no problem.
What I'm trying to do is to insert these 3 values inside my $data variable.
I tried using array merge, and a For each loop with multiple instances but no luck so far.
I obtained my variables like this:
if (isset($_POST['date'])){
$date = $_POST['date'];
$date = json_encode($date);
$date = json_decode($date);
}
if (isset($_POST['shift'])){
$shift = $_POST['shift'];
$shift = json_encode($shift);
$shift = json_decode($shift);
}
if (isset($_POST['val1'])){
$val1 = $_POST['val1'];
$val1 = json_encode($val1);
$val1 = json_decode($val1);
}
if (isset($_POST['data'])){
$dat = $_POST['data'];
$data = json_decode($dat, true);
}
$values = array($date,$shift,$val1);
$r = (array_merge($data, $values));
My data array looks something like this:
Array (
[0] => Array (
[data] => Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => Mat1
[5] => Box1
[6] => 100
[7] => 100
[8] => Piece1
[9] => Loc1
[10] => Mach1
[11] => 1000
[12] => Accepted
)
)
)
[1] => 2019-04-09
[2] => First
[3] => Value1
)
But what I want to achieve is this:
Array (
[0] => Array (
[data] => Array (
[0] => Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => Mat1
[5] => Box1
[6] => 100
[7] => 100
[8] => Piece 1
[9] => Suc1
[10] => Mach1
[11] => 1000
[12] => Accepted
[13] => 2019-04-09
[14] => First
[15] => Value1
)
)
)
)
What am I doing wrong? Or How can I achieve what I'm trying to do?
Edit: Since I can get more than one array at my array, something like this
Array (
[0] => Array (
[data] => Array (
[0] => Array (...)
[1] => Array (...)
[2] => Array (...)
[3] => Array (...)
)
)
)
I just added this code to #HelgeB answer, I'm leaving it here in case someone might need it in the future.
$count = count($data[0]['data']);
for ($i=0; $i < $count ; $i++) {
$data[0]['data'][$i][] = $date;
$data[0]['data'][$i][] = $shift;
$data[0]['data'][$i][] = $val1;
}
As far as I can see from your merged output, your $data array structure is $data[0]['data'][0] = [1,2,3,...,'Accepted'].
So in my opinion you need to insert the values exactly on the level $data[0]['data'][0] to obtain your result.
The simplest way to achieve this would be:
$data[0]['data'][0][] = $date;
$data[0]['data'][0][] = $shift;
$data[0]['data'][0][] = $val1;
If you want to use your merge approach you need to merge on the correct level like this:
$r = [0 => ['data' => [0 => (array_merge($data[0]['data'][0], $values))]]];

extracting data from multidimensional array via PHP and store in text file

I would like to extract data from the following JSON arrays, to a variable that i would like to use to create a text file
Array
(
[0] => Array
(
[0] => 0
[1] =>
)
[1] => Array
(
[0] => 0
[1] => 123:
)
[2] => Array
(
[0] => 0
[1] => TICKET
)
[3] => Array
(
[0] => 0
[1] => ------------------------------------------------
)
[4] => Array
(
[0] => 1
[1] => user 1
)
[5] => Array
(
[0] => 1
[1] => info x
)
[6] => Array
(
[0] => 0
[1] => ------------------------------------------------
)
[7] => Array
(
[0] => 0
[1] => TEXT 1
)
[8] => Array
(
[0] => 0
[1] => TEXT 2
)
[9] => Array
(
[0] => 0
[1] => TEXT 4
)
[10] => Array
(
[0] => 1
[1] => TEXT 4
)
[11] => Array
(
[0] => 0
[1] => TEXT 5
)
[12] => Array
(
[0] => 0
[1] => TEXT 6
)
[13] => Array
(
[0] => 0
[1] => TEXT 7
)
[14] => Array
(
[0] => 0
[1] => TEXT 8
)
[15] => Array
(
[0] => 0
[1] => TEXT 9
)
)
I use the following PHP, but only the array 15 value is returned in my text file.
$ticket = file_get_contents('php://input');
$ticket_output = json_decode($ticket,true);
$ticket_output_def = $ticket_output['ticket'];
$ticket_output_txt = print_r($ticket_output_def,true);
foreach ($ticket_output_def as $array){
$array0 = $array[0];
$array1 = $array[1];
$text = $array0 . $array1;
}
$filename = "output.txt";
file_put_contents($filename, $text);
Well that's normal since you reset $text at every loop iteration!
Maybe try this :
$ticket = file_get_contents('php://input');
$ticket_output = json_decode($ticket,true);
$ticket_output_def = $ticket_output['ticket'];
$ticket_output_txt = print_r($ticket_output_def,true);
$text = "";
foreach ($ticket_output_def as $array){
$array0 = $array[0];
$array1 = $array[1];
$text .= $array0 . $array1;
}
$filename = "output.txt";
file_put_contents($filename, $text);
You are resetting the value of $text in each iteration as #zoubida13 said. As the counter increases, text value is changed to concatenation of elements corresponding to that counter. You can try the method provided by #zoubida13, or you can also use FILE_APPEND as third parameter inside file_put_contents and the code will go like this
`
$ticket = file_get_contents('php://input');
$ticket_output = json_decode($ticket,true);
$ticket_output_def = $ticket_output['ticket'];
$ticket_output_txt = print_r($ticket_output_def,true);
$filename = "output.txt";
foreach ($ticket_output_def as $array) {
$array0 = $array[0];
$array1 = $array[1];
$text = $array0 . $array1;
file_put_contents($filename, $text,FILE_APPEND);
}
`
BUT, this will be an inefficient method I reckon, as it will try to write to the file each time. Its better to concat the text in each iteration and write it after the loop has executed.
I found the solution. You have to use the PHP_EOL; Predefined Constant
$text = $text . $array0 . $array1 . PHP_EOL;

Combining arrays with common values

I have an array of dates that looks like this:
Array
(
[0] => '2014-01-01'
[1] => '2014-01-02'
[2] => '2014-01-03'
[3] => '2014-01-04'
[4] => '2014-01-05'
[5] => '2014-01-06'
[6] => '2014-01-07'
)
and I have another array of dates and counts that looks like this:
[All] => Array
(
[0] => Array
(
[count] => 2
[date] => 2014-01-06
)
[1] => Array
(
[count] => 1
[date] => 2014-01-03
)
[2] => Array
(
[count] => 43
[date] => 2013-12-11
)
[3] => Array
(
[count] => 103
[date] => 2013-12-10
)
[4] => Array
(
[count] => 128
[date] => 2013-12-09
)
[5] => Array
(
[count] => 75
[date] => 2013-12-08
)
[6] => Array
(
[count] => 107
[date] => 2013-12-07
)
I want to make a new associative array where all the keys are the dates from the first array above and all of the values are either the count matched up with the corresponding date or "0".
So for instance, the new array would look like this:
Array
(
[2014-01-01] => 0
[2014-01-02] => 0
[2014-01-03] => 1
[2014-01-04] => 0
[2014-01-05] => 0
[2014-01-06] => 2
[2014-01-07] => 0
)
Does that make sense? Please feel free to ask any questions you may have. Thank you!
Try this code:
$result = array();
foreach($firstArray as $f){
foreach($secondArray as $s){
if($s['date'] == $f) $result[$f] = $s['count'];
}
if(!array_key_exists($f, $result)) $result[$f] = 0;
}
$result = array();
foreach($secondArray as $s){
if(in_array($s['date'], $firstArray) {
unset($firstArray[$s['date']]);
$result[$s['date']] = $s['count'];
}
}
// if items left in first array that are not found within foreach:
if (!empty($firstArray))
$result = array_merge($result, array_fill_keys($firstArray, 0));
// sort by key so dates go ascending
ksort($result);
$new = array();
foreach($all as $row)
{
$new[$row['date']] = $row['count'];
}
array_merge ($new, $old);
Here $all is the array with the date and count indices.
$old is the exisisting array.
That's a 2-liner:
// use dates as index and set everything to 0
$result = array_fill_keys($x, 0));
// copy over existing counts
array_walk($all, function($v) use (&$result) { if (array_key_exists($v['date'], $result)) { $result[$v['date']] = $v['count'];}});

Remove first levels of identifier in array [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 10 months ago.
I think this has been up before, but could'nt find any answer to it. If it's already answered please point me in the right direction with a link.
I have an array that I wan't to remove the first levels of identifier. I think there is a function for this?
Example of how it is:
[0] => Array
(
[8] => Röd
)
[1] => Array
(
[8] => Blå
)
[2] => Array
(
[6] => Bobo
)
[3] => Array
(
[8] => Grön
)
[4] => Array
(
[7] => Sten
)
[5] => Array
(
[8] => Vit
)
[6] => Array
(
[7] => Guld
)
[7] => Array
(
[6] => Lyxig
)
What I wan't
[8] => Röd
[8] => Blå
[6] => Bobo
[8] => Grön
[7] => Sten
[8] => Vit
[7] => Guld
[6] => Lyxig
Try to merge array with splat operator:
print_r(array_merge(...$array));
The problem here is preserving the keys for the identifier you want. You have some names strings that have the same key (like Blå and Röd). You either need to store these in an array or be willing to lose the key.
Example with php5.3:
$processed = array_map(function($a) { return array_pop($a); }, $arr);
This will give you:
[0] => Röd
[1] => Blå
[2] => Bobo
[3] => Grön
[4] => Sten
[5] => Vit
[6] => Guld
[7] => Lyxig
It has become clear the keys on the inner array need to be preserved because they are some kind of id. With that said you must change the end structure you're going for because you can have 2 of the same key in a single array. The simplest structure then becomes:
[8] => Array
(
[0] => Röd,
[1] => Blå,
[2] => Vit,
[3] => Grön
)
[6] => Array
(
[0] => Bobo,
[1] => Lyxig
)
[7] => Array
(
[0] => Sten,
[1] => Guld
)
To get this structure a simple loop will work:
$processed = array();
foreach($arr as $subarr) {
foreach($subarr as $id => $value) {
if(!isset($processed[$id])) {
$processed[$id] = array();
}
$processed[$id][] = $value;
}
}
PHP array_column
$new_array = array_column($old_array,0);
This will retrieve the value at index 0 for each array within $old_array. Can also be using with associative arrays.
use :
public function remove_level($array) {
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $value);
}
}
return $result;
}
which will return second level array values in the same order of the original array.
or you can use array_walk
$results = array();
array_walk($array, function($v, $k) use($key, &$val){
array_merge($results, $v);
});
Below code will also achieve the same result.
$resultArray = array_map('current',$inputArray);
OR
$resultArray = array_map('array_pop',$inputArray);
Note: I have ignored OP's expected result keys. Because it is not possible to have the same keys in the array. The last key will replace the previous one if the same.
foreach($array as $key=>$val) {
$newarr[$val] = $array[$key][$val];
}
untested!
Check this out this is what expected result
<?php
$arrData = array(
"5" => array
(
"8" => "Vit"
),
"6" => array
(
"7" => "Guld"
)
);
foreach($arrData as $key=>$value):
foreach($value as $k=>$v):
$data[$k] = implode(',',$arrData[$key]);
endforeach;
endforeach;
print_r($data);
?>

How to group multidimensional array by sub-array value in and reassign keys in PHP

I looked at all the similar questions and samples (there are many) but still can't get this to work (though I think I am close).
I have an array of employee schedules pulled from a text file...
schedule.txt:
123,Joe,20120208,0845,1645
123,Joe,20120209,0800,1600
456,Sue,20120208,0900,1700
456,Sue,20120209,0700,1500
...
My code to generate the array is:
$schedule = file_get_contents('./schedule.txt');
$s = explode("\n", $schedule);
for ($i = 0; $i < count($s); $i++) {
$s[$i] = explode(",", $s[$i]);
}
print_r($s);
Output is:
Array
(
[0] => Array
(
[0] => 123
[1] => Joe
[2] => 20120208
[3] => 0845
[4] => 1645
)
[1] => Array
(
[0] => 123
[1] => Joe
[2] => 20120209
[3] => 0800
[4] => 1600
)
[2] => Array
(
[0] => 456
[1] => Sue
[2] => 20120208
[3] => 0900
[4] => 1700
)
[3] => Array
(
[0] => 456
[1] => Sue
[2] => 20120209
[3] => 0700
[4] => 1500
)
)
I am instead trying to group employees by Id in a new multidimensional array with output like this:
Array
(
[123] => Array
(
[0] => Array
(
[0] => Joe
[1] => 20120208
[2] => 0845
[3] => 1645
)
[1] => Array
(
[0] => Joe
[1] => 20120209
[2] => 0800
[3] => 1600
)
)
[456] => Array
(
[0] => Array
(
[0] => Sue
[1] => 20120208
[2] => 0900
[3] => 1700
)
[1] => Array
(
[0] => Sue
[1] => 20120209
[2] => 0700
[3] => 1500
)
)
)
I cannot for the life of me wrap my head around how to change my existing array into this new (different) output...
I am trying this but getting nowhere:
$newArr = array();
foreach($s as $k => $v) {
if(!isset($newArr[$v[0]])) {
$newArr[$v[0]] = array();
}
$newArr[$v[0]][] = array($v[0]);
}
Though my output is now:
Array
(
[123] => Array
(
[0] => Array
(
[0] => 123
)
[1] => Array
(
[0] => 123
)
)
[456] => Array
(
[0] => Array
(
[0] => 456
)
[1] => Array
(
[0] => 456
)
)
)
Any thoughts? I know I am missing something in my code around the line:
$newArr[$v[0]][] = array($v[0]);
I tried changing it to:
$newArr[$v[0]][] = array(0 => $v[1], 1 => $v[2], 2 => $v[3], 3 => $v[4]);
which gives my the right output, but I now get undefined offset errors. Plus, if the number of keys in the sub array changes, this code is now limited to the 4 I explicitly entered...
this should be enough, if I understood you right :)
$lines = file('./schedule.txt');
$employees = array();
foreach ($lines as $line)
{
$chunks = explode(',', $line);
$employees[$chunks[0]][] = array_slice($chunks, 1);
}
print_r($employees);
There is a function called fgetcsv to easily grab comma separated values. No need to do it yourself.
This code also solves your problem and properly handles blank lines:
if (($handle = fopen("schedules.csv", "r")) !== FALSE) {
$schedules = array();
while (($data = fgetcsv($handle)) !== FALSE) {
if ($data[0] !== null) { //blank lines return an array containing null
$schedules[$data[0]][] = array_slice($data, 1);
}
}
fclose($handle);
//do what you need to
} else {
// file failed to open
}
Note that I named the file .csv instead of .txt. I'd recommend that you save things that are comma separated values as .csv files. Maybe even define what each column is in the file as well.
<?php
//read the file into an array with each line being an entry
$schedule = file('./schedule.txt');
//empty array
$s = array();
//loop through file lines
foreach($schedule as $row){
//explode on comma
$row = explode(",", trim($row));
//if the id doesn't exist yet...
if(!isset($s[$row[0]])){
//...make it an empty array
$s[$row[0]] = array();
}
//add the row under the id
$s[$row[0]][] = $row;
}
print_r($s);
?>
You can use fscanf:
$handle = fopen('./schedule.txt', 'r');
$employees = array();
while ($line = fscanf($handle, '%d,%s')) {
$employees[$line[0]][] = explode(',', $line[1]);
}
fclose($handle);
print_r($employees);

Categories