How would I setup an associative array to reference specific values at different sections of a page. My function:
<?php
function park_data($park_page_id) {
$data = array();
if($park_page_id){
$data = mysql_fetch_assoc(mysql_query("SELECT * FROM `park_profile` WHERE `park_id` = $park_page_id"));
return $data;
}
}
?>
My print_r:
<?php
print_r (park_data(1));
?>
Produces the following associative array:
Array ( [park_id] => 1 [park_name] => Kenai Fjords [park_address] => 1212 4th Avenue [park_city] => Seward [park_state] => Alaska [park_zip] => 99664)
How would I print just the [park_name] value from this array?
From the docs:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
// on PHP 5.4
print_r(park_data(1)['park_name']);
// earlier versions
$tmp = park_data(1);
print_r($tmp['park_name']);
$park=park_data(1);
echo $park['park_name'];
To output custom formatted text in general, and in this case to output only a single array's key value, use echo, because print_r() called on an array displays the whole array's structure and content, and that's not what you want:
<?php
// code
$park_data=park_data(1);
echo $park_data["park_name"];
// code
?>
Related
$nesAry=array();
$nesAry["name"]="abc";
$nesAry["email"]="abc#email.com";
$nesAry1=array();
$nesAry1["name"]="abc1";
$nesAry1["email"]="abc1#email.com";
$nesAry2=array();
$nesAry2["name"]="abc2";
$nesAry2["email"]="abc2#email.com";
$responseAry = array();
$responseAry[0]=$nesAry;
$responseAry[1]=$nesAry1;
$responseAry[2]=$nesAry2;
echo json_encode($responseAry); // here output like this => [{"name":"abc","email":"abc#email.com"},{"name":"abc1","email":"abc1#email.com"},{"name":"abc2","email":"abc2#email.com"}]
unset($responseAry[1]);
echo "------------removed 1--------";
echo json_encode($responseAry); // but here output like this => {"0":{"name":"abc","email":"abc#email.com"},"2":{"name":"abc2","email":"abc2#email.com"}}
I want Out put Like this after removing an element \n [{"name":"abc","email":"abc#email.com"},{"name":"abc2","email":"abc2#email.com"}]
Please Help me
Try to regenerate your array after unset an item:
$nesAry=array();
$nesAry["name"]="abc";
$nesAry["email"]="abc#email.com";
$nesAry1=array();
$nesAry1["name"]="abc1";
$nesAry1["email"]="abc1#email.com";
$nesAry2=array();
$nesAry2["name"]="abc2";
$nesAry2["email"]="abc2#email.com";
$responseAry = array();
$responseAry[0]=$nesAry;
$responseAry[1]=$nesAry1;
$responseAry[2]=$nesAry2;
echo json_encode($responseAry); // __here output like this => [{"name":"abc","email":"abc2#email.com"},{"name":"abc1","email":"abc1#email.com"},{"name":"abc2"}]__
unset($responseAry[1]);
$responseAry = array_values($responseAry); //regenerate array(reindexing)
echo "------------removed 1--------";
echo json_encode($responseAry); //[{"name":"abc","email":"abc#email.com"},{"name":"abc2","email":"abc2#email.com"}]
EDIT:
As other option you can use array_splice method http://php.net/manual/en/function.array-splice.php
$nesAry=array();
$nesAry["name"]="abc";
$nesAry["email"]="abc#email.com";
$nesAry1=array();
$nesAry1["name"]="abc1";
$nesAry1["email"]="abc1#email.com";
$nesAry2=array();
$nesAry2["name"]="abc2";
$nesAry2["email"]="abc2#email.com";
$responseAry = array();
$responseAry[0]=$nesAry;
$responseAry[1]=$nesAry1;
$responseAry[2]=$nesAry2;
echo json_encode($responseAry); // __here output like this => [{"name":"abc","email":"abc2#email.com"},{"name":"abc1","email":"abc1#email.com"},{"name":"abc2"}]__
array_splice($responseAry,1,1);
echo "------------removed 1--------";
echo json_encode($responseAry);
Your array when first converted to json is a so called "associative" array, and json_encode then exports it to the object you see in the first echo.
After your unset, the array is changed to a "numeric" array and json_encode will export the array with array keys.
Php it self does not care about how the array is used, but json_encode does.
You can use
echo json_encode(array_values($responseAry));
Or not change the final array you want to export
When I put print_r($data); I get the following
Array
(
[name] => Cheese
)
Is there a way to get the key name in a variable on its own?
There may be occasions that name could be email and other values.
Use array_keys():
var_dump(array_keys($data));
Return all the keys or a subset of the keys of an array
Do you mean you know the value but you don't know the key? If so you could write something like this:
$array = ['name' => 'Cheese'];
array_flip($array);
var_export($array['Cheese']); // Output: name
You can have the array key extracted to their own variables using the extract function. For example
$a = array("color"=>"blue");
extract($a);
echo $color;
I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];
I'm new to PHP and I was asked to write a function that accepts an array as a parameter and then prints the array in reverse order. Here is what I have so far:
<?php
function RevOrder ($arr1) {
$arr1 == array();
echo array_reverse($arr1);
}
RevOrder (array(1,4,2,5,19,11,28));
?>
It is supposed to output 28, 11, 19, 5, 2, 4, 1 but I keep getting an array to string conversion error.
echo expects a string while you are passing an array, hence the array to string conversion error. It also looks like you are not properly checking if the param passed is an array. Try this:
<?php
function RevOrder($arr1) {
if (is_array($arr1)) {
return array_reverse($arr1);
}
return false;
}
$reversedArray = RevOrder(array(1,4,2,5,19,11,28));
// Option 1
print_r($reversedArray);
// Option 2
echo(implode(', ', $reversedArray));
<?php
function RevOrder (array $arr1) {
echo implode(", ", array_reverse($arr1));
}
RevOrder (array(1,4,2,5,19,11,28));
But note that this isn't particularly good design - your functions should do one thing. In this case you should instead write a function to print an array according to your liking and then pass it reversed array. Although in this case I guess it's ok to have a helper function for printing the array in reversed order but when you're doing something more complicated you should consider this.
EDIT:
You could do something like this:
function printArray(array $arr){
echo implode(", ", $arr);
}
printArray(array_reverse($arr));
As for why you can't just echo array see this
Arrays are always converted to the string "Array"; because of this,
echo and print can not by themselves show the contents of an array. To
view a single element, use a construction such as echo $arr['foo'].
See below for tips on viewing the entire contents.
Also I added type-hints for array so that when you pass something that's not an array you get an error.
When a retrieve the according data from the database then encode it as json then pass it to the view:
$json_data = json_encode($x);
$search_results['search_results'] = $json_data;
$this->load->view('findquestions',$search_results);
If I display this in the view we get:
[{"question_title":"java"},{"question_title":"big java book"}]
How can the question_titles so "java" be extracted and presented as a url link or inside a table
Since you're passing the json-string directly to the view and then process it (for display) through PHP, you should be able to use PHP's json_decode() to convert it into an object (or array) to use it in a more-friendly manner:
// use json_decode with `true` to get an associative array
$results = json_decode($search_results['search_results'], true);
You can now access the data either directly or within a loop:
// direct access
$title1 = $results[0]['question_title'];
// in a loop
foreach ($results as $result) {
echo 'Title: ' . $result['question_title'];
}
For reference, using the sample-data supplied in the question, a print_r() of the data:
print_r($results);
Array (
[0] => Array (
[question_title] => java
)
[1] => Array (
[question_title] => big java book
)
)
To process the results in PHP
In your controller:
$search_results['search_results'] = $x; //store the array
$this->load->view('findquestions',$search_results); //pass the results as PHP array to view
In your view:
foreach($search_results as $result){
echo $result['question_title'];
}