I'm new in PHP (and in programming altogether). I have watched a video explaining the basics, so I decided to play around with PHP by myself; I wrote this code:
<?php
$people = [
array("John", "smart"),
array("Mike", "dumb"),
array("Jose", "smart"),
array("Emmanuel", "dumb")
];
foreach ($people as $name => $intelligence) {
};
echo $name [0][0]." "."is ". $intelligence[0][1];
?>
I'm trying to output:
John is smart
However, it outputs:
is m
I'm not sure how to fix this.
Please help, thank you.
Your array data (per item) looks like this:
[
'john',
'smart'
]
There is no key association to these values. So in your output example, what you actually need to do is:
foreach ($people as $el)
{
echo $el[0]. ' is ' .$el[1];
}
Your data is a numerically indexed array, starting at 0. So 0 = john and 1 = smart.
It would be better to structure your array like this:
$people = [
0 => [
'name' => 'john',
'intelligence' => 'smart'
], # etc.
];
foreach ($people as $el)
{
echo $el['name']. ' is ' .$el['intelligence'];
}
here we're using named keys that make sense.
In your code example you do this:
foreach ($people as $name => $intelligence)
but $name in your loop is actually the item key.. so 0, 1 etc. and intelligence is the array. Not the name and intelligence as you think.
However, if you're literally just trying to echo out the first element, just do:
echo $people[0][0]. ' is ' .$people[0][1];
I think this is what you meant:
<?php
$people = [
array("John", "smart"),
array("Mike", "dumb"),
array("Jose", "smart"),
array("Emmanuel", "dumb")
];
foreach ($people as $person) {
echo $person[0] ." is ". $person[1]."<br/>";
}
Your people array is fine if that's really the way you want to write it.
You could instead declare it like the following. As another exercise, why don't you declaring the array like this and they modify the rest of the code so it prints what you want.
$people = [
"John" => "smart",
"Mike" => "dumb",
"Jose" => "smart",
"Emmanuel" => "dumb"
];
Your echo statement was outside of the for loop. I moved it inside.
The way you were reading your people array didn't seem quite right, so I've changed it to:
$person[0] - Get the zeroth element in the inner array, the name
$person[1] - Get the first element in the array, the intelligence
Change this
<?php
$people = [
array("John", "smart"),
array("Mike", "dumb"),
array("Jose", "smart"),
array("Emmanuel", "dumb")
];
foreach ($people as $name => $intelligence) {
};
echo $name [0][0]." "."is ". $intelligence[0][1];
?>
to this
$people = [
"John" => "smart",
"Mike" => "dumb",
"Jose" => "smart",
];
foreach ($people as $name => $intelligence) {
echo $name." is ". $intelligence;
};
You can create a simple function passing it params eg. Name to find and array of people.
<?php
$people = [
["John", "smart"],
["Mike", "dumb"],
["Jose", "smart"],
["Emmanuel", "dumb"]
];
function return_Sentence( $name , $array ){
foreach ($array as $details) {
if($name == $details[0]){
return $details[0] . ' is ' . $details[1];
}
}
return 'Not Found';
}
echo return_Sentence( "John" , $people );
?>
Related
An app developer would like to receive data from my API in the following JSON format:
{"response":1,"values":[{"brid": 31,"description": "Painter"},{"brid":33,"description":"Plumber"}]}
I managed to produce this:
{"result":[{"response":1},{"brids":["1","2","3","4","5"]},{"descriptions":["Plumber","Carpenter","Electrician","Mason","Painter"]}]}
By using this code:
$result=array();
$result[]['response']=intval(1);
$result[]['brids']=$brids;
$result[]['descriptions']=$descriptions;
$response["result"]=$result;
echo json_encode($response);
And I managed to produce this:
{"response":1,"0":{"brid":1,"description":"Plumber"},"1":{"brid":2,"description":"Carpenter"},"2":{"brid":3,"description":"Electrician"},"3":{"brid":4,"description":"Mason"},"4":{"brid":5,"description":"Painter"}}
by using this code:
$test=array();
$test['response']=intval(1);
for ($i=0;$i<count($brids);$i++)
{
$value=array();
$value['brid']=intval($brids[$i]);
$value['description']=$descriptions[$i];
$test[]=$value;
}
echo json_encode($test);
How do I satisfy the developer?
Albert
Loop over one of the arrays (both have to be of the same size) a foreach is simplest using the form that captures the key $i in your code.
Build a temp array containing the inner objects
Then simpy add them to the outer array
$descriptions = ["Plumber","Carpenter","Electrician","Mason","Painter"];
$brids = [31,32,33,34,35];
$out['response'] = 1;
foreach ( $brids as $i => $brid ){
$t = ['brid' => $brid, 'description' => $descriptions[$i]];
$out['values'][] = $t;
}
echo json_encode($out);
RESULT
{
"response":1,
"values":[
{"brid":31,"description":"Plumber"},
{"brid":32,"description":"Carpenter"},
{"brid":33,"description":"Electrician"},
{"brid":34,"description":"Mason"},
{"brid":35,"description":"Painter"}
]
}
You were almost there. You just need to wrap your values array into a key in existing response.
$test=array();
$test['response']=intval(1);
$testValues=array()
for ($i=0;$i<count($brids);$i++)
{
$value=array();
$value['brid']=intval($brids[$i]);
$value['description']=$descriptions[$i];
$testValues[]=$value;
}
$test['values']=$testValues;
echo json_encode($test);
you're pretty close, this should work:
$test = [
'response' => 1,
'values' => []
];
for ($i=0;$i<count($brids);$i++){
$test['values'][] = (object) [
'brid' => intval($brids[$i]),
'description' => $descriptions[$i]
];
}
echo json_encode($test);
so instead of pushing directly to $test with $test[], you push to its value attribute
Be aware that $descriptions[$i] inside the for it's a bit risky, there might be few elements in $descriptions than in $birds (at least for the code you have provided)
This is my array:
$customer_info=[
array(
'name'=>array(
'fistname'=>'jason',
'lastname'=>'jason'
),
'id'=>'1'
),
array(
'name'=>'name2',
'id'=>'1'
)
];
and I want to get firstname and lastname from this array .
array_column($customer_info, 'name') should give you an array of all 'name' elements in your 2d array. I'll edit the answer if you can explain better what you want to do here.
If you really want to do it with a foreach loop, simply:
$output = [];
foreach ($customer_info as $row) {
$output[] = $row['name']
}
Should be fairly straight-forward, but we are looping through your array, checking if 'name' is an array or a string, and handling both scenarios.
This will display the information on the page, I wasn't sure if this is what you wanted or if you wanted to store the information into an array for use later.
If you want this stored as an array, what is the format of the array you need, are you going to concatenate the first and last names or store them in a multi-dimensional array?
foreach($customer_info as $key => $customer) {
if(is_array($customer['name'])) {
echo 'First Name: ' . $customer['name']['firstname'] . '.<br />';
echo 'Last Name: ' . $customer['name']['lastname'] . '.<br />';
} else {
echo 'Name is: ' . $customer['name'] . '.<br />';
}
}
this should work fine:
for first array:
$name = $customer_info[0]['name']['fistname'];
$family = $customer_info[0]['name']['fistname'];
for second array:
$name = $customer_info[1]['name'];
I have the following array:
print_r($all_projects);
--------------------------------
Array (
[0] => Array (
[pro_id] => 7
[0] => 7
)
[1] => Array (
[pro_id] => 20
[0] => 20
)
)
How do I grab each pro_id in a foreach loop?
I can find quite a bit information online on how to create an array, and how to grab the key and value from an array. But I have difficulty grabbing the value of a key in an array, in an array.
I currently have this for each:
foreach ($all_projects as $project => $project_id){
echo $project_id;
}
Which in turn returns the following:
Array
Array
This makes sense to me, but how do I go deeper in the array?
foreach($all_projects as $project) {
echo $project['pro_id'];
}
try:
foreach ($all_projects as $project => $project_id){
echo $project_id['pro_id'];
}
or even cleaner to read :
foreach ($all_projects as $project){
echo $project['pro_id'];
}
foreach($all_projects as $KEY => $VALUE) {
echo "KEY: $KEY - PRO_ID: {$VALUE['pro_id']}";
}
In your case, you'd want:
foreach ($all_projects as $project_id => $project) {
echo $project_id . " = " . $project['pro_id'];
}
Now with PHP5.5, you have an easy way to do it:
foreach ($all_projects as list($id))
echo $id;
And the old way:
foreach ($all_projects as $project)
echo $project['pro_id'];
Hope it'll help you!
If we're looping through the $all_projects with foreach loop this way,
foreach ($all_projects as $key => $project) {
echo($key);
}
then $key will actually be 0, 1, etc., not 7 or 20 -- as you might intended this to be -- and $project will be the content of the project.
In your case, I presume that the "project id" you desired are stored inside the "project" array itself, so as other suggested, you should write something like
foreach($all_projects as $project) { // omitting the $key part since you don't need it
echo($project['pro_id']);
}
this will print the actual "project id", which is the pro_id that you want.
If you were to improve this code, you might want to restructure your $all_projects this way
$all_projects = array();
$all_project[7] = $some_project; // your first project with id 7
$all_project[20] = $some_other_project; // your second project with id 20
then you will be able to use your original code to loop through:
foreach($all_projects as $project_id => $project) {
echo($project_id);
}
with $project_id be 7, 20, etc., and $project be the content of your project.
Hope this answers your question!
I am trying to solve the following problem:
Note I am new to programming and PHP and working through SAMS PHP, MySQL and Apache (Julie C. Meloni).
There is an exercise where a multidimensional array has to be created. The outer array is an associative array listing the genres of movies. The genre arrays list movies of that genre. You are then asked to print out a list of genres with the list of films associated with that genre.
My code:
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
$gKeys = array_keys($genres);
foreach ($gKeys as $genre) {
print $genre."<br/>";
}
?>
This works and prints out:
Science Fiction
Drama
Crime
Here's where I am running into a wall. When I try adding another foreach loop after
print $genre;
no results appear in the browser (except results of first loop). I have tried everything. For example:
starting by using the array_value() function applied to $genre and then try a foreach on the array returned.
In the textbook there is also a while (list($x) = ($y)) mechanism mentioned.
I thoroughly re-read the array chapter and have looked elsewhere to no avail.
perhaps I have structured the multidimensional array incorrectly? Do the second dimensional arrays need to be associative arrays also for consistency?
Your array is structured correctly. You're taking wrong array (array of just the keys) and adding another foreach loop after print $genre; hence it is not working.
No, it is not required for second dimensional arrays to be associative arrays as well.
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
foreach ($genres as $genre => $movies)
{
print $genre . " - <br/>";
foreach ($movies as $movie)
{
print $movie . "<br/>";
}
print "</br>";
}
?>
Wait! Why are you doing:
$gKeys = array_keys($genres);
This just gives you a single array of keys.
Do your first loop on $genres, then inside:
foreach ($genre as $key=>$subgenre)
{
//do stuff here
}
foreach ($genres as $genrekey => $genrevalue) {
print $genrekey."<br/>";
foreach ($genrevalue as $value) {
print $value."<br/>";
}
}
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$gKeys = multiarray_keys($genres);
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
Your outer array is an associative array with genres as keys.
To print out movies of that genre (the subarrays), use another foreach as follows:
print "<ul>";
foreach ($genres as $genre => $movies) {
print "<li>".$genre."<ul>";
foreach ($movies as $movie) {
print "<li>".$movie."</li>";
}
print "</ul></li>";
}
print "</ul>";
If you need this for seeing what data goes in an array for debugging purposes you could use PHPs var_export(), var_dump(), print_r() only to make sure the data is getting populated as you want it to. Otherwise if you want to show it in production you could do some like this:
foreach($multiDimentinalArray as $key => $value):
if(is_array($value)):
foreach($value as $k => $val):
print " $key.$k => $val";
else:
print "$key => $value";
endif;
endforeach;
I have an array which is of the following form in PHP-
Array(
0 =>
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
))
and I want it to appear as-
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
)
So how to do it?
Have you tried...
$inner_array = $outer_array[0];
var_dump($inner_array);
...?
Read here in the manual about more details to arrays in php.
Multidimensional arrays generally work as shown below
$shop = array( array("rose", 1.25 , 15),
array("daisy", 0.75 , 25),
array("orchid", 1.15 , 7)
);
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2];
The syntax of foreach construct is as follow:
foreach ($array_expression as $value) {
statement
}
foreach ($array_expression as $key => $value) {
statement
}
The first form loops over the array given by $array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one so that on the next loop, the next element is accessed.
The second form does the same thing, except that the current element’s key will be assigned to the variable $key on each loop.
The foreach syntax above is also similar to the following while construct:
while (list(, $value) = each($array_expression)) {
statement
}
while (list($key, $value) = each($array_expression)) {
statement
}
Even for loop can be used to process and loop through all elements of arrays with the following syntax:
$count = sizeof($arr_expression);
for ($i = 0; $i < $count; $i++) {
$value = $arr_express[$i];
statement
}
for ($i = 0, $item = ''; false != ($value = $arr_expression[$i]); $i++) {
statement
}
Nested loop of “foreach” can also be used to access multidimensional arrays. Here’s an example array and the way to access its value data. For example:
foreach ($array_expression as $arr_value) {
foreach ($array_value as $value) {
statement
}
}
Here’s an example code to access an array:
$contents = array(
"website_1" => array("name" => "StackOverFlow",
"url" => "http://www.stackoverflow.com",
"favorite" => "yes"),
"website_2" => array("name" => "Tip and Trick",
"url" => "http://www.tipandtrick.net",
"favorite" => "yes")
);
To retrieve the data, programmers can specify the keys that lead to the value directly with the following syntax, which will print the “My Digital Life”.
echo $contents['website_1']['name'];
However, the syntax above becomes unpractical when dealing with large arrays, or when the name of the keys and values changed dynamically. In this case, the “foreach” function can be used to access an array recursively.
foreach ($contests as $key => $list) {
echo "Website No.: " . $key . "\n";
echo "Name: " . $list['name'] . "\n";
echo "URL: " . $list['url'] . "\n";
}
The output will be:
Website No.: website_1
Name: StackOverFlow
URL: http://www.stackoverflow.com/
Website No.: website_2
Name: Tip and Trick
URL: http://www.tipandtrick.net/