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
Related
I'm trying to construct an array where there only strings and the array would look like this
key->key->value
To explain it I attached two screenshots below.
I start with this:
After my code below I'm 90% there, yet there is an array in value on the third level instead of simple value.
Here is some code:
$theme = ThemeHandler::with('sections.settings')->find($activeTheme);
$themeSettings = $theme->sections;
$themeSettings = collect($themeSettings->toArray());
// dd($themeSettings);
$themeSections = [];
foreach ($themeSettings as $key => $value) {
$settings = collect($value['settings']);
$settings = $settings->mapToGroups(function ($item) {
return [$item['key'] => $item['value']];
});
$themeSections[$value['key']] = $settings->toArray();
}
dd($themeSections);
I would like to end up with this structure
key->key->value
and not
key->key->single_element_array->value
I'm not sure how I end up with an array at the bottom level when I do this
return [$item['key'] => $item['value']];
inside the mapToGroups, which is a function found here: https://laravel.com/docs/5.8/collections#method-maptogroups
Maybe I misunderstand how mapToGroups work. Anybody has an idea how to get key->key->value structure output?
Use mapWithKeys() instead of mapToGroups().
You're getting an array instead of the simple value you expect because the value is a group, albeit a group with only one member.
mapToGroups() groups all the values with the same key, but mapWithKeys() will assign a single value to each key.
You can see in the examples in the collection documentation, mapToGroups() produces a result like this:
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
And mapWithKeys() result is like this:
[
'john#example.com' => 'John',
'jane#example.com' => 'Jane',
]
I have this array:
$datas = array(
array(
'id' => '1',
'country' => 'Canada',
'cities' => array(
array(
'city' => 'Montreal',
'lang' => 'french'
),
array(
'city' => 'Ottawa',
'lang' => 'english'
)
)
)
);
Question 1:
How can I get the the country name when I have the id ?
I tried: $datas['id'][1] => 'country'
Question 2:
How can I loop in the cities when I have the id ?
I tried:
foreach ($datas as $data => $info) {
foreach ($info['cities'] as $item) {
echo '<li>'.$item['city'].'</li>';
}
}
Thanks a lot.
You have the ID of the array you want analyse, but your array is structured as a map, meaning that there are no keys in the outer array. You will therefore have to iterate the array first to find the object you are looking for.
While the first approach would be to search for the object that has the ID you are looking for, i suggest you map your arrays with their IDs. To do that, you can use two PHP array functions: array_column and array_combine.
array_column can extract a specific field of each element in an array. Since you have multiple country objects, we want to extract the ID from it to later use it as a key.
array_combine takes two arrays with the same size to create a new associative array. The values of the first array will then be used as keys, while the ones of the second array will be used as values.
$mappedCountries = array_combine(array_column($datas, 'id'), $datas);
Assuming that the key 1 is stored in the variable $key = 1;, you can afterwards use $mappedCountries[$key]['country'] to get the name of the country and $mappedCountries[$key]['cities'] to get the cities, over which you can then iterate.
if there might be many arrays in $datas and you want to find one by id (or some other key) you can do something like this:
function search($datas, $key, $value) {
foreach($datas as $data) {
if ($data[$key] === $value) {
return $data;
}
}
So if you want to find where id = 1
$result = search($datas, 'id', '1');
and then you can get country echo $result['country'] or whatever you need.
My PHP call is storing a table from mySQL with the following code.
while (mysqli_stmt_fetch($stmtMyCountTotals)) {
$stmtMyCountTotalsrow = array(
'IndividualUnitsCounted' => $IndividualUnitsCounted,
'IndividualUnitsAdjusted' => $IndividualUnitsAdjusted
);
$stmtMyCountTotalsrows[] = $stmtMyCountTotalsrow;
}
$stmtMyCountTotals->close();
I can not seem to pull a individual value from it. For Example If I want to pull a number from column 1 row 2. I know this is a basic question but I can not seem to find an answer.
This is a multidimensional array, so you would access it like so:
$row1col2 = $stmtMyCountTotalsrows[1][2]
$row2col1 = $stmtMyCountTotalsrows[2][1]
But since it is associative you would want:
$var = $stmtMyCountTotalsrows[1]['IndividualUnitsCounted'];
If you want to access it by column, then you would need to retrieve the column names first into an array:
$cols = array_keys($stmtMyCountTotalsrows[0]);
$var = $stmtMyCountTotalsrows[1][$cols[1]]
// ^ where this is the column number
There are no column numbers in your array, the second dimension is an associative array. So it should be:
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsCounted']
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsAdjusted']
You have an array inside another array. Or a multidimensional array. It looks like this:
Array(
0 => Array(
'IndividualUnitsCounted' => 'Something',
'IndividualUnitsAdjusted' => 'Something Else'
),
1 => Array(
'IndividualUnitsCounted' => 'Yet another something',
'IndividualUnitsAdjusted' => 'Final something'
),
...
...
)
If this array is called $stmtMyCountTotalsrows:
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something"
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something Else"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Yet another something"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Final something"
If you don't know the name of the columns beforehand, you could use current() for the first:
echo current($stmtMyCountTotalsrows[1]);
Alternatively, use array_slice():
echo current(array_slice(stmtMyCountTotalsrows, 0, 1));
I have an array that outputs like this:
1 =>
array
'quantity' => string '2' (length=1)
'total' => string '187.90' (length=6)
2 =>
array
'quantity' => string '2' (length=1)
'total' => string '2,349.90' (length=8)
I would like to loop through each array keys and retrieve the set of 3 values relating to them, something like this (which doesnt work):
foreach( $orderItems as $obj=>$quantity=>$total)
{
echo $obj;
echo $quantity;
echo $total;
}
Would someone be able to give some advice on how I would accomplish this, or even a better way for me to be going about this task. Any information relating to this, including links to tutorials that may cover this, would be greatly appreciated. Thanks!!
foreach( $orderItems as $key => $obj)
{
echo $key;
echo $obj['quantity'];
echo $obj['total'];
}
Using the above.
You need to read the docs on forEach() a little more, since your syntax and understanding of it is somewhat incorrect.
$arr = array(
array('foo' => 'bar', 'foo2', 'bar2'),
array('foo' => 'bar', 'foo2', 'bar2'),
);
foreach($arr as $sub_array) {
echo $sub_array['foo'];
echo $sub_array['bar'];
}
forEach() iteratively passes each key of the array to a variable - in the above case, $sub_array (a suitable name, since your array contains sub-arrays). So within the loop body, it's that you need to interrogate.
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.