foreach function for more than 2 array - php

I need to insert data to a table.. the data come from different sources. The following are my code.
$title = array(Book A, Book B, Book C);
$number = array(2,1,4);
$lines = array(Maria, Smith, Abner);
for($i=1; $i<count($lines); $i++)
{
print '<tr>';
print '<td>'.$title[$i].'</td>';
print '<td>P'.$number[$i].'</td>';
print '<td>['.$lines[$i].']</td>';
print '<td></td>';
print '</tr>';
}
Seems not working :/ the array not display properly in my table.
I'm expecting output as follows:
------------------------------------------------
| Title | No | Lines | Remarks |
------------------------------------------------
| Book A | 2 | Maria | |
| Book B | 1 | Smith | |
| Book C | 4 | Abner | |
------------------------------------------------
at the moment.. I get the following output:
------------------------------------------------
| Title | No | Lines | Remarks |
------------------------------------------------
| Book A | 2 | Maria | |
| | | Smith | |
| | | Abner | |
------------------------------------------------

If your arrays has different keys you can 'reset' them to be zero-based. Just use $array = array_values($array). Quote from manual
array_values() returns all the values from the array and indexes the array numerically.
After this you code will work. This is how your example can be modified:
$title = array('Book A', 'Book B', 'Book C');
$number = array("a" => 2, "b" => 1, "c" => 4);
$lines = array('Maria', 'Smith', 7 => 'Abner');
/* At this point you have some arrays with unknown keys.
It can be [0 => item, 1 => item2] or ['name' => item, 'name2' => item2]
or even with skipped keys [0 => item, 7 => item2]
*/
// Reset keys for all arrays. Now all arrays will contain keys 0, 1, 2 etc.
$title = array_values($title);
$number = array_values($number);
$lines = array_values($lines);
for($i = 0; $i < count($lines); $i++) // Note, arrays now are zero-based, you must start from $i = 0
{
print '<tr>';
print '<td>'.$title[$i].'</td>';
print '<td>P'.$number[$i].'</td>';
print '<td>['.$lines[$i].']</td>';
print '<td></td>';
print '</tr>';
}

you just put i=0; because array started from 0 index and try following code may it help u.
<?php $title = array('Book A','Book B','BookC');$number = array('2','1','4');$lines = array('Maria','Smith','Abner');for($i=0;$i<count($lines); $i++){print '<tr>';print '<td>'.$title[$i].'</td>';print '<td>P'.$number[$i].'</td>';print'<td>['.$lines[$i].']</td>';print '<td></td>'; print '</tr>'; } ?>

There's a neat trick to merging separate arrays with array_map() if you pass null as the first argument, followed by the arrays you want merged.
As quoted in Example #4 in the docs:
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
Using your example for context:
<?php
$titles = ['Book A', 'Book B', 'Book C'];
$numbers = [2,1,4];
$lines = ['Maria', 'Smith', 'Abner'];
// create an 'array of arrays'
$rows = array_map(null, $titles, $numbers, $lines);
var_dump($rows);
Yields:
array (size=3)
0 =>
array (size=3)
0 => string 'Book A' (length=6)
1 => int 2
2 => string 'Maria' (length=5)
1 =>
array (size=3)
0 => string 'Book B' (length=6)
1 => int 1
2 => string 'Smith' (length=5)
2 =>
array (size=3)
0 => string 'Book C' (length=6)
1 => int 4
2 => string 'Abner' (length=5)
You can then iterate over it pretty easily, like so:
foreach ($rows as $row) {
list($title, $number, $line) = $row;
printf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
$title, $number, $line);
}
This should give you something like:
<tr><td>Book A</td><td>2</td><td>Maria</td></tr>
<tr><td>Book B</td><td>1</td><td>Smith</td></tr>
<tr><td>Book C</td><td>4</td><td>Abner</td></tr>
A useful side-effect of this approach is that your arrays do not have to be the same length; null will be used where applicable to pad out any "missing" values.
Another quick example:
<?php
$letters = range('a', 'd'); // ['a', 'b', 'c', 'd']
$numbers = range(1, 3); // [1, 2, 3]
$merged = array_map(null, $letters, $numbers);
var_dump($merged);
Yields:
array (size=4)
0 =>
array (size=2)
0 => string 'a' (length=1)
1 => int 1
1 =>
array (size=2)
0 => string 'b' (length=1)
1 => int 2
2 =>
array (size=2)
0 => string 'c' (length=1)
1 => int 3
3 =>
array (size=2)
0 => string 'd' (length=1)
1 => null
Hope this helps :)

You can try modifying you code as follow:
foreach($lines as $z => $value)
{
print '<tr>';
print '<td>'.$title[$z].'</td>';
print '<td>P'.$number[$z].'</td>';
print '<td>['.$value.']</td>';
print '<td></td>';
print '</tr>';
}

I found that the array index for all my array is not in sequential.
eg: $title =
array[0] = Book A
array[5] = Book B
array[9] = Book C
So, that is probably the reason why it is not display accordingly. I cannot use function 'for'. However, I cannot re-number the index because its the key for me to continue with next module/function.
So, I tried the following code.. but seems something missing..
$i=0;
if (!empty($title)){
foreach($title as $key => $value){
$y = $number[$key];
if ($i<count($lines))
{ $z = $lines[$i];
$i+1;
}
print '<tr>';
print '<td>'.$value.'</td>';
print '<td>'.$y.'</td>';
print '<td>['.$z.']</td>';
print '<td></td>';
print '</tr>';
}
}
The following is the output that I get. Now array for $lines that didn't display properly.
------------------------------------------------
| Title | No | Lines | Remarks |
------------------------------------------------
| Book A | 2 | Maria | |
| Book B | 1 | Maria | |
| Book C | 4 | Maria | |
------------------------------------------------

Related

converting a related database table object into a nested array - PHP

i have some dummy related data in my table "you can take a look at it bellow". i want to nest the data according to their relationships into one array.
Table Data:
+-----+------+--------+
| uid | name | parent |
+-----+------+--------+
| 1 | A | 0 |
| 2 | B | 1 |
| 3 | C | 1 |
| 4 | D | 2 |
| 5 | E | 3 |
| 7 | G | 3 |
| 9 | H | 4 |
| 10 | I | 4 |
| 11 | J | 7 |
+-----+------+--------+
the array is going to be like array('A' =>array('B'=>'D','C'=>array(...)).
am currently using codeigniter and here is what i've done
CODE
public function nestDataIntoArray($id)
{
$this->db->where('uid', $id);
$query = $this->db->get('binary_tbl');
$result = [];
if ($query->num_rows() > 0) {
foreach ($query->result() as $k) {
// secondLevel deep
$secondLevel = $this->getSubLevel($k->uid);
$secondLevelRowCount = $secondLevel->num_rows();
if ($secondLevelRowCount > 0 ) {
if ($secondLevelRowCount > 1) {
foreach ($secondLevel->result() as $key) {
// create second level deep array
$result[$k->name][$key->name][] = $this->getSubLevel($key->uid)->row('name');
// thirdLevel deep
$thirdLevel = $this->getSubLevel($key->uid);
$thirdLevelRowCount = $thirdLevel->num_rows();
if ($thirdLevelRowCount > 0) {
if($thirdLevelRowCount > 1){
foreach ($thirdLevel->result() as $tKey) {
// create third level deep array
$result[$k->name][$key->name][$tKey->name] = $this->getSubLevel($tKey->uid)->row('name');
}
}else{
foreach ($thirdLevel->result() as $tKey) {
$result[$k->name][$key->name][$tKey->name] = $this->getSubLevel($tKey->uid)->row('name');
}
}
} else {
$result[$k->name][$key->name] = $this->getSubLevel($key->uid)->result_array();
} //end thirdLevel deep
}
}
} else {
$result[$k->name] = $this->getSubLevel($key->uid)->row('name');
} // end second level deep
}
} else {
$result = NULL;
}
return $result;
}
private function getSubLevel($id)
{
return $this->db->select('*')->from('binary_tbl')->where('supermember', $id)->get();
}
upon invoking the nestDataIntoArray(1) method i got the following output
OUTPUT
array (size=1)
'A' =>
array (size=2)
'B' =>
array (size=2)
0 => string 'D' (length=1)
'D' => string 'H' (length=1)
'C' =>
array (size=3)
0 => string 'E' (length=1)
'E' => null
'G' => string 'J' (length=1)
this output seems to be fine but i really dont want that Zero index and some of the data still has one or two data related to them which i still have to loop through to get and that to me just seems to be alot of unnecessary coding. So the question is: which other better way can i achieve this and how do i get rid of that zero index?

PHP: Adding multiple associative arrays to another array

Here's a sample of data
Date | Source | Amount
-----------------------
01A | S1 | 12
01A | S4 | 2
01A | S7 | 134
02A | S1 | 126
03A | S4 | 10
02A | S7 | 0
02A | S1 | 3
02A | S4 | 4
02A | S7 | 5
The resulting array needs to look like:
Array
(
[01A] => Array
(
[S1] => 12
[S4] => 2
[S7] => 134
)
[02A] => Array
(
[S1] => 126
[S4] => 10
[S7] => 0
)
[03A] => Array
(
[S1] => 3
[S4] => 4
[S7] => 5
)
)
I've tried looking at pages such as PHP Adding multiple associative arrays to new array based on key, PHP multiple arrays to one associative array and Merge multiple associative arrays to a single array of associative arrays and playing around with code as below (not using the same data - but same theory) but it's not producing what I need. The code below just shows A and B
$array = Array();
$a=array( "ABC" => array("A"=>"RED","B"=>"GREEN"));
$b=array( "ABC" => array("C"=>"BLUE","D"=>"YELLOW"));
$array = $a + $b;
echo '<pre>';
print_r($array);
echo '</pre>';
KISS
$result = array();
foreach($rows as $row)
{
if(!isset($result[$row['Date']])) $result[$row['Date']] = array();
$result[$row['Date']][$row['Source']] = $row['Amount'];
}
Assuming you already have the data in the $input array, the code is as easy as:
$result = array();
foreach ($input as $row) {
$date = $row['Date'];
if (! array_key_exists($date, $result)) {
$result[$date] = array();
}
$result[$date][$row['Source']] = $row['Amount'];
}
If you don't have the data in $input but you fetch it from the database just replace the line:
foreach ($input as $row) {
with something that matches your data retrieval loop, f.e.:
while ($row = mysqli_fetch_assoc($result)) {

PHP Array merge two keyed arrays into a single array

I am two arrays both containning 4 keyed values. They both have the same columns - how would I merge them like so:
Array 1:
Author|Download|Rating|Count
person|23 | 5 | 0
peter |45 | 4 | 0
Array 2:
Author|Download|Rating|Count
| 0 |0 | 3
| 0 |0 | 5
Becomes a single array:
Author|Download|Rating|Count
person|23 | 5 | 3
peter |45 | 4 | 5
This is done via two SQL Queries like shown:
Array 1
while ($stmt->fetch())
{
$array = array (
'Author' => $author,
'Download' => $download,
'Rating' => $rating,
'Count' => '',
);
}
Array 2
while ($stmt->fetch())
{
$array = array (
'Author' => '',
'Download' => '',
'Rating' => '',
'Count' => $count,
);
}
How would I get these into a single Array?
I know one could do this via loop but is there an easier way to do this?

2 attribute in 2-dimensional array php

I want to create a 2 dimensional array, which the second array has 2 attributes. Is it possible in php? Becuase I know it's possible in Pascal
example
| Doc | Term |
| 0 | 0 => 'Term1' |
| | 1 => 5 |
----------------------------
| 1 | 0 => 'Term'2' |
| | 1 => 2 |
My question is, How to create this 2-dimensional array and how to access each value?
Thank you
This is simple array nesting:
$a = array(array('Term1', 5), array('Term2', 2));
$a[1][1] === 2;
This is an extremely basic question. Consider consulting a php book or tutorial.
Yes, you just make the value of the item in the array, another array, you can do this as deep as you like. e.g.,
Creating the array
$doc = array(
array(
'Term1',
5
),
array(
'Term 2',
2
)
)
Since no ID is set, the id's are automatically generated, starting at 0. You can set the ID if you want like this:
$doc = array(
0 => array(
3 => 'Term1',
9 => 5
),
1 => array(
3 => 'Term 2',
10 => 2
)
)
Retrieving data from the array
$term1 = $doc[0][0];
echo $term1; // outputs 'Term 1'

Summarize array in PHP

I'm mainly programming in language that used for business systems, and there is a useful built-in function that can sum an array. For example, we've got array like this:
red | 1
red | 1
green | 1
orange | 2
orange | 1
orange | 1
blue | 1
After using summarizing function we get
red | 2
green | 1
orange | 4
blue | 1
Is it equivalent function in php?
UPD.
$array = array('red'=>1,'red'=>2,'green'=>1....);
In php
red | 1
red | 1
green | 1
orange | 2
orange | 1
orange | 1
blue | 1
This kind of array is not possible. PHP array can not have multiple index keys with the same name. It will override the previous one.
As said, an array like
array('red'=>1,'red'=>2,'green'=>1....);
is not possible. Try it and make a print_r. You will see that there is only one red entry with value 2 (or what ever the last value is). The last one will overwrite the previous ones.
Depending on how you create the array, you can either sum the value on the fly, e.g.
for(...) {
if(!isset($array[$color])) {
$array[$color] = 0;
}
$array[$color] += $value;
}
or create a multidimensional array:
$array = array(
'red'=> array(1,2),
'green'=> array(1),
...
);
You can then array_map to loop over it and compute the sums of each entry with array_sum:
$newarray = array_map('array_sum', $array);
Your initial array should contain only values. You can use array_values() for that. After that you can count the values with array_count_values()
http://php.net/manual/en/function.array-count-values.php
supposed you have array like this:
$array = array(
'red | 1',
'red | 1',
'green | 1',
'orange | 2',
'orange | 1',
'orange | 1',
'blue | 1'
);
You can process it this way:
<?php
//process the array data
$temp_output = array();
foreach( $array as $raw)
{
list($name, $value) = array_map('trim', explode("|", $raw));
if( !isset($temp_output[ $name ] ) )
$temp_output[ $name ] = (int)$value;
else
$temp_output[ $name ] += (int)$value;
}
//now, print the value
foreach( $temp_output as $key => $data)
{
echo "{$key} | {$data}\n";
}
?>

Categories