How can I display an array in a readable format? - php

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

Related

I cant figure out this array_map issue I am having

**EDIT:
I am trying to display the number of keys in my arrays that start with a "P", "M" and "D". I think I should be using array_maps and have some luck with it but I am now stuck and tried looking through the manual, on here and w3schools with no luck.
I'm using version 5.6.36 of PHP with XAMPP on a local server. I've tried playing around with array_maps which I think is the right command to use, but I just cant get my head around how to use it properly. I've read the manual on it, looked on here, looked on youtube and W3Schools with no luck. Can anyone help please?
I have this array:
$tasks = array
(
0 => 'P1',
1 => 'M1',
2 => 'D1',
3 => 'P2',
4 => 'D2'
);
I want it to display this:
Array
(
[P] => 2
[M] => 1
[D] => 2
)
See how it returns the number of P's M's and D's nice and neatly?
From what I understand, the solution code should be something like this:
$array2 = array_map(function(???????){
return ??????????;
}, $tasks);
$array2a = (array_count_values($array2));
echo "<pre>"; print_r($array2a); echo "</pre>";
Please help?!
you can use array_map as following :
$tasks = array
(
0 => 'P1',
1 => 'M1',
2 => 'D1',
3 => 'P2',
4 => 'D2'
);
$charsToCheck = array('P','M','D');
$result = array_map(function($v) use ($charsToCheck){
if(in_array(substr( $v, 0, 1),$charsToCheck))
return substr( $v, 0, 1);
}, $tasks);
print_r(array_count_values($result));
Result:-
Array
(
[P] => 2
[M] => 1
[D] => 2
)
The function array_map() creates one output element from every input element. Since you don't want that, it is the wrong tool. Probably the easiest way to achieve your goal is to use a simple loop. However, if things get more complicated, this may not scale well. For those cases, array_reduce() could come in handy:
$input = [
0 => 'P1',
1 => 'M1',
2 => 'D1',
3 => 'P2',
4 => 'D2',
];
$frequency = array_reduce(
$input,
function ($carry, $item) {
$initial = substr($item, 0, 1);
if (array_key_exists($initial, $carry)) {
$carry[$initial] += 1;
}
return $carry;
},
[
'P' => 0,
'M' => 0,
'D' => 0,
]
);
echo json_encode($frequency, JSON_PRETTY_PRINT) . PHP_EOL;
The point of this is that it defines what to do with a single element ($item) and how to modify the resulting state ($carry) in a single function, keeping this part away from the iteration part. Since this avoids mutable state, this can also be seen as a functional (as in "functional programming") approach.
You cannot use array_map for that... You could use reduce I guess but here's a fast and easy way... Basically you create your new array and do the counting according to the first letter of your tasks array.
$list = new Array();
foreach($tasks as $task){
if($list[$task{0}]){
$list[$task{0}]++;
}else{
$list[$task{0}] = 1;
}
}
The problem you'd get with array_map is that it would always produce a 1:1 ratio of your array, which is not what you want...
(sorry for the bad PHP if it is, been ages...)
EDIT:
Using your edited question, here's your possible usage:
$array2 = array_map(function($val){
return $val{0};
}, $tasks);
The key to both answers is the $var{0} part, this extracts the character at index 0...

How to echo form data from array

For a wordpress form I look for the entries using:
<?php
print_r($entry); exit;
?>
This gives me:
Array ( [1.1] => 2015 [1.2] => Infiniti [1.3] => Q70 )
How do I write the full php to echo these chosen entries individually that are entered on the form (from a 3 stage chained select field).
I have read this PHP, how to echo specific object data from array? and for his scenario he needs:
echo $arr['name_en'][0];
But I have no apparent 'name_en' equivalents
I am new to php so if I need to define my version of $arr help with that for this scenario would be great $arr = $entry['field'] or something?
If this is your array
Array (
[1.1] => 2015,
[1.2] => Infiniti,
[1.3] => Q70
)
To print single values in PHP you have to use a syntax like this:
echo $array_name[1.1];
echo $array_name[1.2];
echo $array_name[1.3];
And the output will be
2015
Infiniti
Q70
Have a look to the official documentation to understand how an array works PHP Manual: Arrays
I am not sure it response to your question.
Here is how to echo all value inside an array.
$arr = array('1.1' => 2015, '1.2' => 'Infiniti', '1.3' => 'Q70');
foreach ($arr as $key => $value) {
echo $value;
}

PHP - from DB to Array format

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); ?>

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']
}

json_encode children items?

How can I use php json_encode to produce the following from an array?
{"issue":{"project_id":"Test Project","subject":"Test Issue"}}
I've been trying for the last 40 mins but I can't get it working for the life of me.
The best I can do is:
$arr = array ("project_id"=>"Baas","subject"=>"Test Issue");
echo json_encode($arr); // {"project_id":"Baas","subject":"Test Issue"}
The problem is making "issue" parent. Any hint on how to accomplish this?
Thanks!
The output you want is essentially an associative array nested in another associative array. So, create that data structure, then encode it.
$child_arr = array("project_id" => "Baas", "subject" => "Test Issue");
$parent_arr = array("issue" => $child_arr);
echo json_encode($parent_arr);
Or, if we're in a one-liner mood today:
$arr = array("issue" => array("project_id" => "Baas", "subject" => "Test Issue"));
echo json_encode($arr);
$arr = array ("issue" => array("project_id"=>"Baas","subject"=>"Test Issue"));

Categories