PHP - from DB to Array format - php

I AM A PHP SUPER NOOB.
I am trying to extract data using PHP from a MySQL db.
I want to take the 'PersonName' column and 'Count' column and place them into an array.
PHP Code (so far):
$result = mysqli_query($con, --SQL CODE HERE--);
while($row = mysqli_fetch_array($result))
{
$data = $row['colName'];
}
I have been using print_r to print out my $data and i have been getting results such as
"Array ( [0] => Fred [Name] => Fred [1] => 11 [count(*)] => 11 )"
in my attempts. This format has not been working for me.
Goal:
I want to obtain an array (or 2 arrays) that contain the data from the 2 columns mentioned above.
I need it to be in either of the following formats:
1. One-Array Solution: [['Fred', 3], ['Bob', 5], ['Ted', 10]]
2. Two-Array Solution: ['Fred', 'Bob', 'Ted'] & [3, 5, 10]
Question:
How should my PHP code be modified in order to bring data in from the database into the array formats that I am looking for?

$dataArray = array();
while($row = mysqli_fetch_array($result))
{
$dataArray[] = $row;
}
Display it this way in your HTML and you will understand how to use the data from the array
<?php print_r($dataArray); ?>

Related

Restructuring Multi Dimensional Array Format

I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}

Multidimensional array loop php

New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with
for ($i = 0, $nums = count($inputs); $i < $nums; $i++)
But once inside of that loop I am lost as to what comes next. Please help.
The array looks as follows:
$inputs =array (
'row' => array (
0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',),
1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',),
What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.
When I use
foreach ($inputs as $key => $row)
I can then do
dd($row['0']);
And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.
You can loop over that data like this:
foreach($inputs as $key => $row) {
echo "row $key:\n";
foreach ($row as $person) {
echo " - " . $person['name'], " is ", $person['age'], " old.\n";
}
}
See it run on eval.in
Output based on the input you provided:
row row:
- shay is 23 old.
- Tim is 30 old.

How can I display an array in a readable format?

I want to write my Array into a readable format.
$result = array_diff($one, $two);
print_r($result);
Array ( [1] => 298GS [2] => 09283 [3] => U4235 )
This is how it should look like:
298GS
09283
U4235
My only idea is to write it like this:
echo $result[1];
echo $result[2];
echo $result[3];
But this is not very useful because I never know how many values my array will have.
There isn't much to say, just loop through the array and show the values. This works for variable number of items
foreach($result as $r){
echo $r."<br>";
}
Since you had difficulties doing such thing, I suggest you to study about the basics of the language (IF, lopps, variables, etc) - maybe that's what you are doing, IDK. Foreach and More.
I use the following function as I can read the keys too, the output showed below is what you'll actually see so it is formatted.
function debugArray($arr)
{
return "<pre>" . var_export($arr, true) . "</pre>";
}
$arr = [
1,
2,
3,
4,
5
];
echo debugArray($arr);
Output
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
)
Actual image of output.
You might want to check json_encode to export your data in json format so you can use it better with UI

Converting a multi-dimensional php array into a JSON array of objects

I need to create a multi-dimensional array in php and want to use it in a jQuery script as a JSON array of objects;
The required output in the jQuery script should look like this:
data = [
{ Month:'April', Comms:1000, Fees:200, Gains: 200},
{ Month:'May', Comms:1200, Fees:300, Gains: 300}
]
Currently my php arrays are generated as follow:
$data1[] = array(
'Month' => 'April',
'Comms' => 1000,
'Fees' => 200,
'Gains' => 200
);
$data2[] = array(
'Month' => 'May',
'Comms' => 1200,
'Fees' => 300,
'Gains' => 300
);
echo json_encode($data);
My question is how to combine data1 and data2 into the data array in the json_encode php function which will produce the required jQuery JSON array of objects?
I do have the values of the different array fields and can create data1 and data2 in a different way, so the data is flexible and I can combine them in any other way which will produce the data array which will output them in the required JSON format.
Any help will be highly appreciated, I have seen question regarding this subject but none which address the issue I am facing.
Simply:
echo json_encode($data1 + $data2);
Note that you can also use + to merge arrays.
You'll want to merge both Arrays into a new Array of Arrays. See the manual for more information.
$data = array_merge($data1, $data2);
echo json_encode($data)
or, more simply by using the + operator:
echo json_encode($data1 + $data2)
Try :
echo json_encode(array_merge($data1, $data2));
Write:
echo json_encode($data1 + $data2);
just user
echo json_encode($data1 + $data2);
You should make another array by extracting data from database by using groupBy months and store the data in other array.
$array = array();
foreach ($data as $element) {
$array[$element['month']][] = [ 'comms' => $element['comms'], 'fees' => $element['fees'], 'gains' => $element['gains']
}

problem with array and GoogChart

ok.. I know I can find help here :)
I am barely out of noobhood so be gentle :)
I'm trying to fetch data from a db and use it to call a pie chart in GoogChart so here is my problem... some code like db connections etc. is skipped to get to the point.
First we look at the array GoogChart uses to pass the info:
$data = array(
'8' => 6,
'3' => 3,
'9' => 2,
);
Now we look at how I am trying to do it pulling the data from a db:
//connect and query here
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// trimmed cuz I can't sort it out
$dat = "'$viewid' => $total_views,"; //problem likely here
}
$data = array(
$dat
);
When I echo the $dat, I get this:
'8' => 6,'3' => 3,'9' => 2,
So theoretically, it should work??? But noop :(
There may be a totally different way of doing this but I'm stumped... didn't take much to do it either lol.
What you're doing is creating an array with one element: "'8' => 6,'3' => 3,'9' => 2,".
Instead, you should be populating an array as you go:
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// use the $viewid as the key and $total_views as the value
$data[ $viewid ] = $total_views;
}
Of course, you could also do (not certain if this could help you, but it is an option):
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
// use the $viewid as the key and $total_views as the value
$data[ trim($row['id']) ] = trim($row['views']);
}

Categories