getting each value of an associative array - php

i need help building a function that display an associative array and i want to insert them in a variable. for example i have this assoc array :
$array[ID] = 1;
$array[Name] = John;
$array[age] = 12;
$array[ID]=2;
$array[Name] = Mary;
$array[age] = 14;
i need to make the ID,name,age as variables so i can display it in a table. when i loop through them each time it fills the table row. it has to be each one a variable coz i need to insert them into a gird and display the grid .. where then i can update delete the info

I'd use one of the answers provided but if you really really want to (again, i don't see a reason but what the hell do i know) use extract()
<?php
$people = array(
array('id' => 1, 'name' => 'John', 'age' => 12),
array('id' => 2, 'name' => 'Mary', 'age' => 14)
);
foreach($people as $row) {
extract($row);
echo "Id: $id, Name: $name, Age: $age\n";
}
//Prints:
//Id: 1, Name: John, Age: 12
//Id: 2, Name: Mary, Age: 14
~

Currently it looks as if you are overwriting the values of the first person with the values of the second person.
What you're looking for is an array structure with more than one dimension, like this:
$people = array(
1 => array('name' => 'John', 'age' => 12),
2 => array('name' => 'Mary', 'age' => 14)
);
Then it'll be easy to print out table rows:
foreach($people as $id => $person){
print '<tr><td>'.$id.'</td><td>'.$person['name'].'</td><td>'.$person['age'].'</td></tr>';
}//foreach
Hope this helps!

foreach($array as $row) {
echo $row['ID'],$row['Name'],$row['age'];
}

Im not sure what you want to do exactly, but maybe it is the extract function you are looking for.

foreach($array as $key => $value){
echo $key. ' = '.$value.";
}
would give you
ID = 1
Name = John
age = 12
etc
Also be sure to do $array["ID"] = ... instead of $array[ID] = ...

You can do:
foreach($array as $user) {
list($age, $name, $id) = array_values($user);
echo $id, $name, $age;
}
But like others already pointed out, this is pointless because you can much more easily read the values directly from the array through their associative keys. You also wouldnt have to run array_values to assign the array values before being able to assign them with list.

Related

PHP MySQL Assign variables to array data

I have the following:
$sql="SELECT course_status, COUNT(course_name) FROM courses GROUP BY course_status";
Then a while loop to store the data:
$menu[] = array(
'sum_status' => $row['COUNT(course_name)'],
'course_status' => $row['course_status']
);
I can print_r($menu) with all data.
How can I assign the keys and values to different variables like:
$status_0 = $key[0] <br>
$count_0 = $value[0] <br>
$status_1 = $key[1] <br>
$count_1 = $value[1] <br>
and so on...?
Thank you!
A little more info, perhaps pasting the code, would be helpful. If I understand it correctly, you could just change your query to:
$sql="SELECT course_status as 'status', COUNT(course_name) as 'count' FROM courses GROUP BY course_status";
Then a simple foreach loop will give you the right display.
I am not entirely understanding your question. But iterating through an array of arrays is a simple as:
<?php
$items = [
[
'foo' => 'Hello',
'bar' => 23
],
[
'foo' => 'Earth',
'bar' => 47
]
];
foreach($items as $item) {
echo $item['foo'];
echo $item['bar'];
}
Output:
Hello23Earth47
Further, rather than assigning to individual variables, you can access an individual item's value by targeting the appropriate key:
echo $items[1]['foo'];
Output:
Earth
To parse the array item in a string, wrap with curlies:
echo "{$items[0]['foo']} Dolly";
Output:
Hello Dolly

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.

PHP Sorting array of arrays based on another user-defined array

Hoping I am not opening a duplicate question but I didn't see this type of question being asked or the answers I saw didn't seem to work with my dataset (but I'm very new at this).
I am hoping to sort the following data set (array of arrays) based on another array of strings.
The code is running and it is only running the generateHtml function for strings that exist in the $ntbooks array which is by design. What I need to solve is how to perform a custom sort using the $ntbooks as the order. Right now, as the code runs and the content is parsed from content.php, the order the data is populated into the menu is the order in which it is seen (top to bottom of array)--I would like to sort the data so that Matthew is written out, then Mark, then Luke, etc.
This is a sample of my data but there are over 250 arrays (contentids) in it and I would like to avoid restructuring or reorganizing my dataset. When all is said and done, the generateHTML should start with matthew, mark, luke, and work its way through the list.
Thank you in advance for your help!
Dynamically Generated HTML Menu (menu.php):
include('content.php');
$main = array();
foreach($articles as $article)
{
foreach(explode("; ", $article["verse"]) as $verseData)
{
$verse = explode(" ", $verseData);
$book = $verse[0];
$verse = explode(":", $verse[1]);
$chapter = $verse[0];
if(empty($main[$book]))
$main[$book] = array();
if(empty($main[$book][$chapter]))
$main[$book][$chapter] = array();
if(empty($main[$book][$chapter][$verse[1]]))
$main[$book][$chapter][$verse[1]] = array();
$main[$book][$chapter][$verse[1]] = array
(
"full" => $article["full"]
);
}
}
$ntbooks = array("Matthew", "Mark", "Luke", "John", "Acts", "Romans", "1Corinthians", "2Corinthians", "Galatians", "Ephesians", "Philippians", "Colossians", "1Thessalonians", "2Thessalonians", "1Timothy", "2Timothy", "Titus", "Philemon", "Hebrews", "James", "1Peter", "2Peter", "1John", "2John", "3John", "Jude", "Revelation");
foreach($main as $book => $data)
{
if (in_array($book, $ntbooks)) {
generateHtml($book, $data);
}
}
function generateHtml($book, $data)
{
echo "<!-- ". $book ." -->\n";
echo "<div class=\"submenu\">\n";
echo "". $book ."\n";
echo "<!-- Level 2 menu -->\n";
echo "<div>\n";
echo "<div>\n";
foreach($data as $chapter => $verses)
{
echo "<div class=\"submenu\">\n";
echo "Chapter ". $chapter ."\n";
echo "<!-- Level 3 menu -->\n";
echo "<div>\n";
echo "<div>\n";
foreach($verses as $verse => $value)
{
echo "Verse ". $verse ."\n";
}
echo "</div>\n";
echo "</div>\n";
echo "</div>\n";
}
}
PHP Array of Arrays (content.php):
$articles = array(
array(
'contentid' => '0',
'full' => 'Item1 by Artist Name1 (Matthew 4)',
'verse' => 'Matthew 4:18-22',
'commentary' => ''),
array(
'contentid' => '1',
'full' => 'Item2 by Artist Name2 (Luke 15)',
'verse' => 'Luke 15:11-14; Luke 15:20-21',
'commentary' => ''),
array(
'contentid' => '2',
'full' => 'Item3 by Artist Name3 (John 3)',
'verse' => 'John 3:1-9',
'commentary' => ''),
array(
'contentid' => '3',
'full' => 'Item4 by Artist Name4 (John 8)',
'verse' => 'John 8:1-15A',
'commentary' => ''),
array(
'contentid' => '4',
'full' => 'Item5 by Artist Name5 (Matthew 27; Luke 23; John 19)',
'verse' => 'Matthew 27:20-23A; Luke 23:20-25A; John 19:2-3A',
'commentary' => 'Here '));
You need to sort using a custom comparison function, where the values being compared will be the keys from the reference array that correspond to the values from the data array.
So if:
$order = ['Matthew', 'Mark', 'Luke'];
and your data array's verse is guaranteed to be one of the above values (in your example this is not true!) then you could do it with
$comparison = function($a, $b) use ($order) {
return array_search($a['verse'], $order) - array_search($b['verse'], $order);
};
usort($data, $comparison);
However, it's not as simple in your case because verse is not as convenient as that. You will need to somehow extract the value of interest out of it, an exercise which I will not attempt to solve because there are too many unknowns (e.g. how is 'Matthew 27:20-23A; Luke 23:20-25A; John 19:2-3A' supposed to be sorted?).
Use usort.
From: http://php.net/manual/en/function.usort.php
bool usort ( array &$array , callable $value_compare_func ).
Basically, you call usort with the array you would like to sort and a function that would indicate the sort order (compare the two objects and determines which one is "greater").
Since the book is in the verse object, you can do something like this:
function sortCompare($obj1, $obj2)
{
$book1 = explode($obj1['verse'])[0];
$book2 = explode($obj2['verse'])[0];
return indexOf($book1, $ntbooks) - indexOf($book2, $ntbooks);
}
At which point you can call
usort($articles, "sortCompare");.
The sortCompare function above might need tweaking but it's a good start.

Merging CSV lines where column value is the same

I have a big CSV file with about 30 columns and 2.5K rows.
Some of the rows have exactly the same values except some columns.
I would like to merge those alike and concatenate with a comma between the values of the columns that are not the same.
Small example:
id name age kid
1 Tom 40 John
1 Tom 40 Roger
---merged becomes---
1 Tom 40 John, Roger
I can do this with PHP using lots and lots of fors and ifs but I am hoping that there's a more elegant and fast way.
This is a great beginner question for a common programming problem. What you'll want to do is a two step approach. First, parse the CSV into a data structure that you can easily modify, then loop over that structure and generate a new array that matches the output.
<?php
// Parse CSV into rows like:
$rows = array(
array(
'id' => 1,
'name' => 'Tom',
'age' => 50,
'kid' => 'John'
),
array(
'id' => 1,
'name' => 'Tom',
'age' => 50,
'kid' => 'Roger'
),
array(
'id' => 2,
'name' => 'Pete',
'age' => 40,
'kid' => 'Pete Jr.'
),
);
// Array for output
$concatenated = array();
// Key to organize over
$sortKey = 'id';
// Key to concatenate
$concatenateKey = 'kid';
// Separator string
$separator = ', ';
foreach($rows as $row) {
// Guard against invalid rows
if (!isset($row[$sortKey]) || !isset($row[$concatenateKey])) {
continue;
}
// Current identifier
$identifier = $row[$sortKey];
if (!isset($concatenated[$identifier])) {
// If no matching row has been found yet, create a new item in the
// concatenated output array
$concatenated[$identifier] = $row;
} else {
// An array has already been set, append the concatenate value
$concatenated[$identifier][$concatenateKey] .= $separator . $row[$concatenateKey];
}
}
// Do something useful with the output
var_dump($concatenated);
If you only have the data in a CSV file, I think that the easiest way to do what you want is build an associative array using the common data as key and modifing it if exists:
$array=[];
while ($a=fgetcsv($handle)){
if (isset($array[$a[0]."-".$a[1]."-".$a[2]])) {
$array[$a[0]."-".$a[1]."-".$a[2]].=",".$a[3];
}
else {
$array[$a[0]."-".$a[1]."-".$a[2]]=$a[3];
}
}

Add 2 values to 1 key in a PHP array

I have a result set of data that I want to write to an array in php. Here is my sample data:
**Name** **Abbrev**
Mike M
Tom T
Jim J
Using that data, I want to create an array in php that is of the following:
1|Mike|M
2|Tom|T
3|Jim|j
I tried array_push($values, 'name', 'abbreviation') [pseudo code], which gave me the following:
1|Mike
2|M
3|Tom
4|T
5|Jim
6|J
I need to do a look up against this array to get the same key value, if I look up "Mike" or "M".
What is the best way to write my result set into an array as set above where name and abbreviation share the same key?
PHP's not my top language, but try these:
array_push($values, array("Mike", "M"))
array_push($values, array("Tom", "T"))
array_push($values, array("Jim", "J"))
$name1 = $values[1][0]
$abbrev1 = $values[1][1]
or:
array_push($values, array("name" => "Mike", "abbrev" => "M"))
array_push($values, array("name" => "Tom", "abbrev" => "T"))
array_push($values, array("name" => "Jim", "abbrev" => "J"))
$name1 = $values[1]["name"]
$abbrev1 = $values[1]["abbrev"]
The trick is to use a nested array to pair the names and abbreviations in each entry.
$person = array('name' => 'Mike', 'initial' => 'M');
array_push($people, $person);
That said, I'm not sure why you're storing the data separately. The initial can be fetched directly from the name via substr($name, 0, 1).
You will need to create a two dimensional array to store more than one value.
Each row in your result set is already an array, so it will need to be added to your variable as an array.
array_push($values, array('name', 'abbreviation'));
maybe you create a simple class for that as the abbreviation is redundant information in your case
class Person
{
public $name;
pulbic function __construct($name)
{
$this->name = (string)$name;
}
public function getAbbrev()
{
return substr($this->name, 0, 1);
}
public function __get($prop)
{
if ($prop == 'abbrev') {
return $this->getAbbrev();
}
}
}
$persons = array(
new Person('Mike'),
new Person('Tom'),
new Person('Jim')
);
foreach ($persons as $person) {
echo "$person->name ($person->abbrev.)<br/>";
}
You could use two separate arrays, maybe like:
$values_names = array();
$values_initials = array();
array_push($values_names, 'Mike');
array_push($values_initials, 'M');
array_push($values_names, 'Tom');
array_push($values_initials, 'T');
array_push($values_names, 'Jim');
array_push($values_initials, 'J');
So you use two arrays, one for each of the second and third columns using the values in the first one as keys for both arrays.
php arrays work like hash lookup tables, so in order to achieve the desired result, you can initialize 2 keys, one with the actual value and the other one with a reference pointing to the first. For instance you could do:
$a = array('m' => 'value');
$a['mike'] = &$a['m']; //notice the end to pass by reference
if you try:
$a = array('m' => 'value');
$a['mike'] = &$a['m'];
print_r($a);
$a['m'] = 'new_value';
print_r($a);
$a['mike'] = 'new_value_2';
print_r($a);
the output will be:
Array
(
[m] => value
[mike] => value
)
Array
(
[m] => new_value
[mike] => new_value
)
Array
(
[m] => new_value_2
[mike] => new_value_2
)
have to set the same value to both Mike and M for keys.

Categories