I am using a database to get the prices as displayed as "Betrag". The actual value of "Betrag" is "18981", but i am converting it by:
$tabledata[] = array('category' => $beschriftung, 'value' => number_format($zeile['summe'], 0, ',', '.').'€', 'id' => $i);
My problem is that i want to get the marked text "Anzahl: 413" below the price, but using the number_format, it doesn't work. I was trying something like $tabledata += or just adding it after the conversion but it didn't get my expected output. It all works with a while loop iterating over the id.
So the actual question is:
Is it possible to add a String to an array without deleting the value which is alredy in it?
Feel free to ask questions or give comments.
Thats the wrong place to fix your "issue". $tabledata is only an array, printed somewhere else and at this point, you have to move the output of your "Betrag". That means of couse, you have to add it to your $tabledata array.
$tabledata[] = array(
'category' => $beschriftung,
'value' => number_format($zeile['summe'], 0, ',', '.').'€',
'id' => $i,
'count' => $betrag
);
and later, you have to print it right after $value. (Something like this..)
foreach ($tabledata as $row) {
// ...
echo $row['value'];
echo "<br />";
echo "Anzahl:" . $row['count'];
// ...
}
But thats only an example and depends on how you build your response (maybe inside an template engine, ...)
Of couse, you could also do the fast and bad way by just append the "Betrag" to the value with a <br /> delimeter.
$tabledata[] = array(
'category' => $beschriftung,
'value' => number_format($zeile['summe'], 0, ',', '.').'€' . '<br />Anzahl: ' . $betrag,
'id' => $i
);
it is possible to add a string to a value which already is in an array - for example
<?php $einArray = array('text1','text2');
$einArray[1] .= "test";
echo $einArray[1];
?>
Will output "text2test".
Is this the answer to your problem?
Related
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.
is this possible? i want to return name and type of a car, in one json element.
The normal way is this,
{
$return = array ('label' => $row['name'],
'Type' => $row['Type'],
);
}
echo json_encode($return);
But i want something like this so i can just call "NameType",
$return = array ('NameType' => $row['Name', 'Type'],
);
the above should normally be like this.
I know my syntax is wrong.
I don't understood well the question, but you can do
$return = array ('NameType' => $row['Name']." ".$row['Type']);
or
$return = array ('NameType' => array($row['Name'], $row['Type']));
Don't know exactly what you want to do
I have an array of the following structure:
$some_array = array(
array(
'font' => 'Arial',
'label' => 'Arial'
),
array(
'font' => 'PT+Sans:400',
'label' => 'PT Sans'
)
);
Let's say that I only know that one item has 'font' value of 'PT+Sans:400' and I need to retrieve the 'label' value of that single item. How can I do it easier than iterating through subarrays?
Since you are already using foreach you just want other alternatives then you can consider this solutions
Solution 1
You can try to filter your search using array_filter
$search = "PT+Sans:400" ;
$array = array_filter($array,function($v)use($search){ return $v['font'] == $search;});
var_dump($array); // returns all found array
Output
array
1 =>
array
'font' => string 'PT+Sans:400' (length=11)
'label' => string 'PT Sans' (length=7)
If you need only the label
$find = array_shift($array); // take only the first
print($find['label']); // output the label
Output
PT Sans
Solution 2
It you are not interested in return the array and all you want is just the label then you should consider array_reduce
$search = "PT+Sans:400" ;
$results = array_reduce($array,function($a,$b)use($search){ return $b['font'] == $search ? $b['label'] : null ; });
print($results);
Output
PT Sans
You need to iterate through the subarrays. Alternatively, if you have control over the data structure where this is getting stored, consider using a hash table (associative array) and then you can just check if a particular key is set.
Keep it simple:
function findLabel($source, $font)
{
foreach ($source as $item) {
if ($item['font'] == $font) {
return $label;
}
}
return null;
}
Usage:
$label = findLabel($some_array, 'PT+Sans:400');
I am new to using multidimensional arrays with php, I have tried to stay away from them because they confused me, but now the time has come that I put them to good use. I have been trying to understand how they work and I am just not getting it.
What I am trying to do is populate results based on a string compare function, once I find some match to an 'item name', I would like the first slot to contain the 'item name', then I would like to increment the priority slot by 1.
So when when I'm all done populating my array, it is going to have a variety of different company names, each with their respective priority...
I am having trouble understanding how to declare and manipulate the following array:
$matches = array(
'name'=>array('somename'),
'priority'=>array($priority_level++)
);
So, in what you have, your variable $matches will point to a keyed array, the 'name' element of that array will be an indexed array with 1 entry 'somename', there will be a 'priority' entry with a value which is an indexed array with one entry = $priority_level.
I think, instead what you probably want is something like:
$matches[] = array(name => 'somename', $priority => $priority_level++);
That way, $matches is an indexed array, where each index holds a keyed array, so you could address them as:
$matches[0]['name'] and $matches[0]['priority'], which is more logical for most people.
Multi-dimensional arrays are easy. All they are is an array, where the elements are other arrays.
So, you could have 2 separate arrays:
$name = array('somename');
$priority = array(1);
Or you can have an array that has these 2 arrays as elements:
$matches = array(
'name' => array('somename'),
'priority' => array(1)
);
So, using $matches['name'] would be the same as using $name, they are both arrays, just stored differently.
echo $name[0]; //'somename';
echo $matches['name'][0]; //'somename';
So, to add another name to the $matches array, you can do this:
$matches['name'][] = 'Another Name';
$matches['priority'][] = 2;
print_r($matches); would output:
Array
(
[name] => Array
(
[0] => somename
[1] => Another Name
)
[priority] => Array
(
[0] => 1
[1] => 2
)
)
In this case, could this be also a solution with a single dimensional array?
$matches = array(
'company_1' => 0,
'company_2' => 0,
);
if (isset($matches['company_1'])) {
++$matches['company_1'];
} else {
$matches['company_1'] = 1;
}
It looks up whether the name is already in the list. If not, it sets an array_key for this value. If it finds an already existing value, it just raises the "priority".
In my opinion, an easier structure to work with would be something more like this one:
$matches = array(
array( 'name' => 'somename', 'priority' => $priority_level_for_this_match ),
array( 'name' => 'someothername', 'priority' => $priority_level_for_that_match )
)
To fill this array, start by making an empty one:
$matches = array();
Then, find all of your matches.
$match = array( 'name' => 'somename', 'priority' => $some_priority );
To add that array to your matches, just slap it on the end:
$matches[] = $match;
Once it's filled, you can easily iterate over it:
foreach($matches as $k => $v) {
// The value in this case is also an array, and can be indexed as such
echo( $v['name'] . ': ' . $v['priority'] . '<br>' );
}
You can also sort the matched arrays according to the priority:
function cmp($a, $b) {
if($a['priority'] == $b['priority'])
return 0;
return ($a['priority'] < $b['priority']) ? -1 : 1;
}
usort($matches, 'cmp');
(Sourced from this answer)
$matches['name'][0] --> 'somename'
$matches['priority'][0] ---> the incremented $priority_level value
Like David said in the comments on the question, it sounds like you're not using the right tool for the job. Try:
$priorities = array();
foreach($companies as $company) {
if (!isset($priorities[$company])) { $priorities[$company] = 0; }
$priorities[$company]++;
}
Then you can access the priorities by checking $priorities['SomeCompanyName'];.
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.