PHP: Adding multiple associative arrays to another array - php

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

Related

How to create PHP array from MySQL table

I have a MySQL table:
-------------------
|type_id|type_name|
-------------------
| 22 | Toyota |
| 22 | Mazda |
| 23 | Volvo |
| 23 | Man |
| 25 | Scania |
| 25 | Iveco |
| 25 | Fiat |
-------------------
which is created dynamically from user input. I want to create an array from the table using PHP like this:
array(
'22' => array('Toyota', 'Mazda'),
'23' => array('Volvo', 'Man'),
'25' => array('Scania', 'Iveco','Fiat'),
);
where array id will be type_id and elements will be type_name's of the type_id.I tried this:
$results = array();
while($line = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$results[] = $line;
}
print_r($results);
But I am getting:
Array (
[0] => Array (
[type_id] => 22
[type_name] => Toyota
)
[1] => Array (
[type_name] => 22
[type_name] => Mazda
)
...so on
Please help!
You need to change your code a bit and it will work fine:-
$results = array();
while($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$results[$line['type_id']][] = $line['Type_name']; //check change here
}
print_r($results);
Note:- check your column-names and correct them if any mistake is there.
Please replace your db name and table name in the code-
$conn = mysqli_connect("localhost","root","","dbname");
$query ="select * from table";
$exe = mysqli_query($conn,$query);
$input = array();
$type = array();
while ($result = mysqli_fetch_array($exe))
{
if(array_key_exists($result['type_id'], $input))
{
$type[] = $result['type_name'];
}
else
{
$type = array($result['type_name']);
}
$input[$result['type_id']] = $type;
}
echo "<pre>";
print_r($input);
select type_id and Type_name columns from table and in foreach loop do this:
$output = array();
foreach ($result as $item){
$output[$item['type_id']][] = $item['Type_name'];
}

combining data from multiple lines into a single array

I have some code which pulls from multiple tables of a MS SQL database, arranges the data and outputs an array, I then need to use that array to populate a worksheet telling someone what items are needed on a day to day basis. Right now the output looks like the below, where the fields are ID, Name, Date, number (they are asterisk deliminated because some names include commas).
74*xxxx*2017-06-04*1
74*xxxx*2017-06-05*1
74*xxxx*2017-06-06*2
74*xxxx*2017-06-07*2
74*xxxx*2017-06-08*2
74*xxxx*2017-06-09*2
74*xxxx*2017-06-10*2
75*yyyy*2017-06-05*123
75*yyyy*2017-06-06*111
75*yyyy*2017-06-07*124
75*yyyy*2017-06-08*107
75*yyyy*2017-06-09*194
75*yyyy*2017-06-10*195
I am trying to get them to merge them into a single value per ID so that I can print it out to a grid to look similar to:
| ID | NAME | 06-04 | 06-05 | 06-06 | 06-07 | 06-08 | 06-09 | 06-10 |
| 74 | xxxx | 1 | 1 | 2 | 2 | 2 | 2 | 2 |
| 75 | yyyy | - | 123 | 111 | 124 | 107 | 194 | 195 |
my intent was to merge the array values into a single array with the dates as the keys, the (most recent) code I was trying is:
$schedule[] = $PID . "*" . $program . "*" . $date . "*" . $num;
$grid = array();
foreach ($schedule as $item ) {
$ex = explode('*', $item);
$grid[$ex[0]] = array(
'name' => $ex[1],
$ex[2] => $ex[3],
);
}
with the intent that that would merge them into a single array line to look like:
[74] => Array ( [name] => xxxx [2017-06-04] => 1 [2017-06-05] => 1 [2017-06-06] => 2 [2017-06-07] => 2 [2017-06-08] => 2 [2017-06-09] => 2 [2017-06-10] => 2)
after which I could just use it line by line with $grid[$i][1] etc to pull the value and print to each cell. I've tried other methods than the above, that is the only one I presently have the code snippet for and I've only been able to get it to keep the last value I add on a per ID basis.
I'm certain there is a piece I am missing or simply not understanding, if anyone could offer some input it would be appreciated.
If I understood your requirement correctly, the below code will give the desired array.
$schedule[] = '74*xxxx*2017-06-04*1';
$schedule[] = '74*xxxx*2017-06-05*1';
$schedule[] = '74*xxxx*2017-06-06*2';
$schedule[] = '74*xxxx*2017-06-07*2';
$schedule[] = '74*xxxx*2017-06-08*2';
$schedule[] = '74*xxxx*2017-06-09*2';
$schedule[] = '74*xxxx*2017-06-10*2';
$schedule[] = '75*yyyy*2017-06-05*123';
$schedule[] = '75*yyyy*2017-06-06*111';
$schedule[] = '75*yyyy*2017-06-07*124';
$schedule[] = '75*yyyy*2017-06-08*107';
$schedule[] = '75*yyyy*2017-06-09*194';
$schedule[] = '75*yyyy*2017-06-10*195';
$grid = array();
foreach ($schedule as $item ) {
$ex = explode('*', $item);
$grid[$ex[0]]['name'] = $ex[1];
$grid[$ex[0]][$ex[2]] = $ex[3];
}
print_r($grid);
And out put is
Array
(
[74] => Array
(
[name] => xxxx
[2017-06-04] => 1
[2017-06-05] => 1
[2017-06-06] => 2
[2017-06-07] => 2
[2017-06-08] => 2
[2017-06-09] => 2
[2017-06-10] => 2
)
[75] => Array
(
[name] => yyyy
[2017-06-05] => 123
[2017-06-06] => 111
[2017-06-07] => 124
[2017-06-08] => 107
[2017-06-09] => 194
[2017-06-10] => 195
)
)

create a subcategories hierarchy from multidimensional array

I have this table in my DB (I hope it's correctly showed):
+++++++++++++++++++++++++++
| id_child |--| id_parent |
+++++++++++++++++++++++++++
| 5 |--| 2 |
| 6 |--| 2 |
| 7 |--| 4 |
| 8 |--| 4 |
| 9 |--| 5 |
| 10 |--| 5 |
| 11 |--| 9 |
| 12 |--| 9 |
---------------------------
I wrote a php recursive function that create a multidimensional array from a parent passed (in this case '2').
So, if I put a print_r I obtain this result:
Array ( [5] => Array ( [9] => Array ( [11] => Array ( ) [12] => Array ( ) ) [10] => Array ( ) ) [6] => Array ( ) )
How I can obtain a structure of this type?
(I exclude the first parent, 2)
(2)
-5
--9
----11
----12
--10
-6
Thanks.
You would need another recursive function to iterate over your array, like so:
function printCategories($categories, $level = 1) {
foreach ($categories as $cat => $subCats) {
echo str_repeat('-', $level) . $cat . "\n";
printCategories($subCats, $level+1);
}
}
printCategories($categories);
<?php
function printtree($tree, $level) {
$prefix=str_repeat('-',$level);
foreach ($tree as $k=>$v) {
echo "$prefix$k<br>\n";
if (is_array($v)) if (sizeof($v)>0) printtree($v,$level+1);
}
}
$tree=array( 5=>array(9=>array(11=>array(), 12=>array()), 10=>array()), 6=>array());
printtree($tree,1);
?>

php Multidimensional array question

So I have an array like the following:
Array
(
[0] => Array
(
[user_id] => 684
[sec_id] => 2
[rank_id] => 1
[rank] => usr
)
[1] => Array
(
[user_id] => 693
[sec_id] => 3
[rank_id] => 5
[rank] => usr
)
)
And I have another array like this
Array
(
[0] => 2
[1] => 7
[2] => 27
)
I want the value of the second array to be added at the end of each arrays of the 1st array, and it should be multiplied. I mean, if I have 100 arrays in the first array, and 3 elements in the second array, I should have 300 in the resulting array.
Taking example of the above, I would like to have something as follows:
user_id | sec_id | rank_id | rank | menu_id
684 | 2 | 1 | usr | 2
684 | 2 | 1 | usr | 7
684 | 2 | 1 | usr | 27
693 | 3 | 5 | usr | 2
693 | 3 | 5 | usr | 7
693 | 3 | 5 | usr | 27
I tried with the following function, but it's not working.
function getR($arr_one,$arr_two) {
foreach ($arr_one as $k=>&$v) {
foreach ($arr_two as $x=>&$y) { $v['menu_id'] = $y; }
}
return $arr_one;
}
This is just making an array like this:
user_id | sec_id | rank_id | rank | menu_id
684 | 2 | 1 | usr | 27
693 | 3 | 5 | usr | 27
Means, it's just adding menu_id at the end of each element of the first array, but not multiplying. Any idea, I'm surely missing something.
Thanks guys.
function getR($arr_one,$arr_two) {
$new_arr = array();
foreach ($arr_one as $k=>$v) {
foreach ($arr_two as $x=>$y) {
$this_item = $v;
$this_item['menu_id'] = $y;
$new_arr[] = $this_item;
}
}
return $new_arr;
}
I'm not going to ask... but try this:
<?php
function crazy ($arr1,$arr2) {
foreach ($arr1 as $key=>$value) {
foreach ($arr2 as $value2) {
$nvalue=$value;
$nvalue[]=$value2;
$new[]=$nvalue;
}
}
return $new;
}
$arr1=array(array('user'=>1,'dude'=>2),array('user'=>2,'dude'=>3));
$arr2=array(2,7,27);
print_r(crazy($arr1,$arr2));
this is tested too, http://www.ideone.com/Of126
Without testing (eek!) I imagine something like this:
function getR( $arr_one, $arr_two )
{
$second_key = 0;
foreach ( $arr_one as $k => &$v )
{
$v['menu_id'] = $second_key++;
if ( 3 == $second_key ) $second_key = 0;
}
return $arr;
}
Presumably, you're passing the first array by reference? Not sure what $arr is that you're returning though...

Create flat array of individual values from rows of comma-separated values fetched from a database table

Please help me to create an array from a field of my DB. That field has records separated by comma. Below is the illustration:
ID | article_title_fld | article_tags_fld |
----------------------------------------------------------------------
1 | Learn PHP | PHP, coding, scripting |
3 | Javascript Tutorial | Javascript, scripting, tutorial |
4 | Styling with CSS | CSS, tutorial, web design |
I want to collect all records in the article_tags_fld then put it into 1 array. Perhaps I named it $array1, and the print out as below:
Array
(
[0] => PHP
[1] => coding
[2] => scripting
[3] => Javascript
[4] => scripting
[5] => tutorial
[6] => CSS
[7] => tutorial
[8] => web design
)
$array1 = array();
$result = mysql_query("SELECT article_tags_fld FROM MY_TABLE");
while ($row = mysql_fetch_assoc($result)) {
$array1 = array_merge($array1, array_map('trim', explode(",", $row['article_tags_fld'])));
}
explode will split a string by a delimiter.
array_merge will combine two arrays.
array_map will apply trim to all elements.
trim will remove any white space on either side of your tags.
Actually, I would normalize the table into multiple tables first.
articles
article_ID | article_title_fld |
----------------------------------------
1 | Learn PHP |
3 | Javascript Tutorial |
4 | Styling with CSS |
tags
tag_ID | tag_title_fld |
------------------------
1 | PHP |
2 | coding |
3 | scripting |
4 | Javascript |
5 | tutorial |
6 | CSS |
7 | web design |
article_tags
article_ID | tag_ID |
---------------------
1 | 1 |
1 | 2 |
1 | 3 |
3 | 4 |
3 | 3 |
3 | 5 |
4 | 6 |
4 | 5 |
4 | 7 |
and then in the PHP
$array1 = array();
$result = mysql_query("
SELECT tag_title_fld
FROM tags
JOIN articles_tags USING(tag_ID)
ORDER BY article.article_ID
");
foreach($result as $row) {
$array1[] = $row['tag_title_fld'];
// With count. See below for the query it goes with
// $array2 = array();
// $array2['tag'] = $row['tag_title_fld'];
// $array2['count'] = $row['tag_count'];
// $array1[] = $array2;
}
Of course, if you just wanted a list of the tags without duplicates, you'd use this query instead.
SELECT tag_title_fld
FROM tags
and if you wanted them with a count of how often they're used:
SELECT tag_title_fld, COUNT(*) AS tag_count
FROM tags
JOIN articles_tags USING(tag_ID)
GROUP BY tag_title_fld
UPDATED
you can do also this way by using mysql_fetch_Array
$array1 = array();
$result = mysql_query("SELECT ID , article_tags_fld FROM my_table");
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
$array1[] = $row['article_tags_fld'];
// OR
// $array1[] = $row[1];
}
ADDED:
in one line:
// use this version to behave as in your example..
$array1 = array_map('trim',explode(',',implode(',',$array1)));
// use this version with array_unique for a non duplicate way...
$array1 = array_unique(array_map('trim',explode(',',implode(',',$array1))));
DISPLAY:
print_r( $array1 );
Array
(
[0] => PHP
[1] => coding
[2] => scripting
[3] => Javascript
[4] => scripting
[5] => tutorial
[6] => CSS
[7] => tutorial
[8] => web design
)
This should output everything.
$pdo = new PDO( /* CONNECTION */ );
$stmt = $pdo->query( 'SELECT article_tags_fld FROM TABLENAME' );
function mapFunc( $row ){ return explode( ',', $row[ 0 ] ) }
$all = array();
foreach( array_map( 'mapFunc', $stmt->fetchAll() ) as $row )
{
$all = array_merge( $all, $row );
}
// $all now holds all of the values.
You should normalize your database table so that you don't have comma-separated values in your rows.
mysql_ functions should no longer be used, so I'll demonstrate mysqli's object-oriented syntax.
If your database values are consistently comma-space separated, then explode() is fine. If you might have leading or trailing spaces in your article_tags_fld values, then you can TRIM() that in your SQL. If you might not have spaces after each comma, then you can explode the strings with preg_split() using a pattern like /, */.
The result set object from a mysqli query is iterable by foreach(), so you can safely avoid making iterated fetch() calls to access the column of data.
By pushing the exploded values with the spread operator (...), the result array will be flat.
If you want to remove duplicate values from the result, you can call array_unique() on the result array after the loop is finished.
Modernized Code: (Full MYSQL + PHP Demo)
$result = [];
foreach ($mysqli->query("SELECT article_tags_fld FROM MY_TABLE") as $row) {
array_push($result, ...explode(', ', $row['article_tags_fld']));
}
var_export(array_unique($result));

Categories