I have an array $rows where each element is a row of 15 tab-delimited values. I want to explode $rows into a 2D array $rowData where each row is an array element and each tab-delimited value is assigned to a different array element. I've tried these two methods without success. I know the first one has a coding error but I do not know how to correct it. Any help would be amazing.
for ($i=0; $i<count($rows); $i++){
for ($j=0; $j<15; $j++){
$rowData = array([$i] => array (explode(" ", $rows[$j])));
}
}
foreach ($rows as $value){
$rowData = array( array (explode(" ", $rows[$value])));
}
$rowData = array();
foreach($rows as $value) {
$rowData[] = explode("\t", $value);
}
for ($j=0; $j<15; $j++) {
$rowData[$j] = explode("\t", $rows[$j]);
}
To expand: The problem with the following code:
$rowData = array([$i] => array (explode(" ", $rows[$j])));
is that you don't appear to know what the different things you've written mean precisely.
A call to array() returns a new array with the indicated elements. So array (explode(" ", $rows[$j])) yields an array with a single element, namely the array returned by explode(). And you're wrapping that in another call to array(), specifying the loop variable $i as the key corresponding to that element. Also, you're using the assignment symbol =, which means that every time you go through the loop, $rowData is being completely overwritten - what you wanted was to add new elements to it without getting rid of the old ones.
Related
I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}
I'm doing something that is perhaps too long and strange to explain, but basically I've mapped a string in a complex way into an array in a way to make them jumbled up. This is an example of how it would look:
field[26][25]='x';
field[24][23]='z';
field[28][29]='y';
Now that I've successfully jumbled up the string in exactly the way I wanted, I need to reconstruct the linear result.
So I need to take row 1 of the array, and loop through all the elements in this row to combine them into a string. Then do the same thing with row 2 and so on to create one massive linear string.
How do I count how many rows and elements in those rows I have? For the life of me I cant even begin to find how to do this for multid arrays.
Kind regards
#u_mulder's got a solid answer there. For the number of elements, you'd just say:
$total = 0;
foreach( $matrix as $row ) $total += count($row);
For the concatenation of elements, you'd just say:
$concat = '';
foreach( $matrix as $row ) $concat .= implode('', $row);
Bob's your uncle. But really, is there a valid use case for such a strange mashup?
$field[26][25]='x';
$field[24][23]='z';
$field[28][29]='y';
$field_string = '';
array_walk_recursive ( $field , function($item, $key) use (&$field_string){
if(!is_array($item)){
$field_string .= $item;
}
});
echo $field_string;
Honestly, this is a little confusing. I may need more info but let me know if this helps
You can start with an empty string and use two nested foreach to iterate over lines and items on each line and append each item to the string:
$result = '';
foreach ($fields as $row) {
foreach ($row as $item) {
$result .= $item;
}
}
Or you can replace the entire inner foreach with $result .= implode('', $row);.
You can even replace the outer foreach with a call to array_map() then implode() the array produced by array_map() into a string:
$string = implode(
'',
array_map(
function (array $items) {
return implode('', $items);
},
$fields
)
);
I am a newbie in this and I have read lots of stuff about this matter (including some topics here), before starting this topic, but I do not quite get it yet, so I will ask for some help (if it is possible) :)
So, in the column that I want to print I have values like this on every row:
value1|value2|value5|value12|value25
value3|value5|value12|value14|value26|value32|value55
value1|value2|value14|value26|value31
The number of rows can be 3 or 1500+... So I want to merge the arrays and print those values sorted and without duplicates: value1, value2, value3, value5, value12, etc...
I have tried to explode the arrays, but I could not find out how to assign a variable to every array and merge them and all I have done is to print all values:
foreach ($rows as $areas) {
foreach (explode('|', $areas->value) as $area) {
var_dump($area);
}
}
Afterwards I have read somewhere this will be very slow if I have many rows (and I am going to have thousands), so I am stuck here and I do not know what else I could do...
I will appreciate any help and direction that you can give me, because it is too hard for me and I can not do it without help
Thank you in advance
You can store each value of your exploded string as key (if it's not an object nor array), it store only unique values. Then you have to just use array_keys() to get keys and sort returned array:
$rows = array(
'value1|value2|value5|value12|value25',
'value3|value5|value12|value14|value26|value32|value55',
'value1|value2|value14|value26|value31'
);
$results = array();
foreach ($rows as $row) {
$items = explode('|', $row);
foreach ($items as $item) {
$results[$item] = 0;
}
}
$results = array_keys($results);
sort($results, SORT_NATURAL);
Live demo on eval.in
There are two ways of doing this:
<?php
$str = 'value1|value2|value5|value12|value25';
$str1 = 'value3|value5|value12|value14|value26|value32|value55';
$str2 = 'value1|value2|value14|value26|value31';
//-- Method 1: Concat and make a single string and then explode and make a single array
$finalString = $str . '|' . $str1 . '|' . $str2;
print_r(array_unique(explode('|', $finalString)));
//-- Method 2: explode first and then merge into a single array
$strArr = explode('|', $str);
$strArr1 = explode('|', $str1);
$strArr2 = explode('|', $str2);
print_r(array_unique(array_merge($strArr, $strArr1, $strArr2)));
Program 1 and Program 2 are supposed to output same values but they are not. Why? How to assign values to array variables before it is being created?
<?php
echo "Program 1.<br>";
$col = array(1,3);
$data = array("123,234,345,456,567", "234,345,456,567,678");
$resultfinal = "";
for($i=0; $i<count($data); ++$i){
$tempdata = explode(',',$data[$i]);
for($j=0; $j<count($col); ++$j){
$resultfinal .= ",".$tempdata[$col[$j]];
}
$resultfinal .= "<br>";
}
echo $resultfinal;
echo "Program 2.<br>";
$resultfinal2 = "";
$resultsub = "";
for($j=0; $j<count($col); ++$j){
$resultsub .= ",".$tempdata2[$col[$j]];
}
for($i=0; $i<count($data); ++$i){
$tempdata2 = explode(',',$data[$i]);
$resultfinal2 .= $resultsub."<br>";
}
echo $resultfinal2;
?>
Output:
Program 1.
,234,456
,345,567
Program 2.
error...
You cannot save CPU time this way.
Think a little about it: you need to process all the items from $data (1 loop over $data). For each item from $data you need to explode it into pieces then extract the values whose indices are stored in $col. This is another loop (over $col) for each item of $data.
The only way to do this is to use two nested loops (outer loop over $data, inner loop over $col) as you already did in program 1.
If you are really concerned about saving CPU time (not a real concern for small and medium amounts of data), you can try using less PHP code and more internal PHP array functions (to move the loops and as much processing as possible into the PHP's native code):
This is a possible solution:
// For array_intersect_key() we need an array having the values of $col as keys
$columns = array_combine($col, $col);
// Store the generated lines here
$output = array();
// The outer loop over $data
foreach ($data as $item) {
// Explode the item into pieces
$pieces = explode(',', $item);
// Move the inner loop into PHP native code; array_intersect_key() keeps
// from $pieces the values having the same keys as $columns
// implode() joins the extracted pieces back into a string
$output[] = implode(',', array_intersect_key($pieces, $columns));
}
// Join the lines with <br>, output them
echo(implode("<br>\n", $output));
I have the following.
while($row = mysql_fetch_array($result))
{
$item = "itemCount_".$row['id'];
if ($_POST[$item] > 0)
{
$items2 = array( $i=> array($row['item'],$row['price']));
$i++;
echo $item." = ".$_POST[$item]." ".$i."<br>";
}
}
I would have thought that this would put each item in a array but it only puts the last item in the loop in. where is my fundamental flaw?
$items2 = array( $i=> array($row['item'],$row['price']));
That just keeps reassigning $items2 to a new array. Don't even worry about the $i counter and use
$items2[] = array($row['item'], $row['price']);
PHP Arrays
You're initializing a new array every time you go through the loop, it's better to use the array_push() function.