Using PHP, how do I output/display the values from this array within my web page:
http://api.getclicky.com/api/stats/4?site_id=83367&sitekey=e09c6cb0d51d298c&type=clicks&output=php&unserialize
Looks like a print_r() output to me.
Use a foreach statement to iterate over the array echoing each as you go
foreach($data as $k => $v) {
echo "{$k} => {$v}";
}
$data is the input data
$k is the key $v is the $value
The above is only useful for a single depth array for an array of arrays like the example data provided you need to use a recursive function then check to see if the value is an array if so call the function recursivally.
If the data structure never changes then some nested loops will do the job. (some people think recursion is evil, I pity them)
DC
Start with our Array
$myarray = array(
"Key1" => "This is the value for Key1",
"Key2" => "And this is the value for Key2"
);
Show All Output (Helpful for Debugging)
print_r($myarray);
/* or */
var_dump($myarray);
Show only a Single Value
print $myarray["Key1"]; // Prints 'This is the value for Key1'
print $myarray[0]; // Prints 'This is the value for Key1'
Related
I have a session called $_SESSION['data']
And I have a text input called 'lengtezijde'
I already used foreach on the session:
foreach ($_SESSION['data'] as $key => $data);
And if I want to use my input from lengtezijde, I tried it like this:
echo $_SESSION['data'][$_GET['key'];
but then it is an array and I want the input value.
How do I go a layer deeper in the array to use the value?
Please try this inside the foreach loop:
echo $data['lengtezijde'];
or
echo $_SESSION['data'][$key]['lengtezijde'];
We have seen $key will have indexing value 0.
Note: as looping on session data you will get $data value as when print $data:
Array ( [hoogte] => 1 [kleur] => 1 [lengtezijde] => 800 [toevoegen] => toevoegen )
So you can get directly the value of lengtezijde by using as :
$data['lengtezijde']; inside the foreach loop.
Try this ....
echo $_SESSION['data'][$key]['lengtezijde'];
It is not clear how you set the value of the array. If you set the array value in the for-loop like this:
foreach ($_SESSION['data'] as $key => $data);
$data['lengtezijde'] = "some value";
Then to get the value you must do something like this:
$key = $_GET['key']; //or the key to the index you want
echo $_SESSION['data'][$key]['lengtezijde'];
contains the following i am trying get array_unique value from multidimensional associative array
Here, i am only showing only sample array which is similar to this.
$array = ['games'=>[['vollyball', 'football'], ['vollyball', 'football'], ['rubby', 'chess']]];
Here is tried so for
foreach ($array as $key => &$value) {
$value = array_unique($value);
}
echo "<pre>";
print_r($array);
echo "</pre>";
exit;
Here i am expecting output is,
$array = ['games'=>[['vollyball', 'football'], ['rubby', 'chess']]];
Here the array should be same even after removing duplicate from multidimensional array.
Thanks for your time and suggestions.
you could try the following:
$a=array_values(array_unique(array_merge(...$array['games'])));
This assumes that all your usable values are below $array['games'].
Edit:
Here is another way, using array_walk:
array_walk($array['games'],function($itm){global $res; $res[json_encode($itm)]=$itm;});
echo json_encode(array_values($res));
I don't like the global $res array very much, but this is a way forward, I believe. In the callback function of array_walk() I add all values to an associative array ($res). The keys are JSON representations of their actual values. This way I will overwrite identical values in the associative array $res and will end up with a set of unique values when I apply the array_values() function at the end to turn it back into a non-associative array.
The result is:
[["vollyball","football"],["rubby","chess"]]
Here is a little demo you can check out: http://rextester.com/JEKE60636
2. edit
Using a wrapper function I can now do without the global variable $res and do the operation in-place, i. e. removing duplicate elements directly from the source array:
function unique(&$ag){
array_walk($ag,function($itm,$key) use (&$ag,&$res) {
if (isset($res[json_encode($itm)])) array_splice($ag,$key,1);
else $res[json_encode($itm)]=1.;
});
}
unique($array['games']);
echo json_encode($array)
This will result in
{"games":[["vollyball","football"],["rubby","chess"]]}
see here: http://rextester.com/YZLEK39965
this might be very simple, and well, yes ... I may not fully understand how objects work, which seems to be the real problem here. So thanks for helping! ^^
I've got an Object that kinda looks like this.
$myobject = Array( [some_random_name] => "Value to that random name" )
Since I'm not sure how those two bits of information are called (sry for that) I will refer to them as "name" and "value". My question is: how do I extract these informations? I need both, the "name" and the "value", so I can store them in two variables ($namevar, $nameval), which should then output something like this:
echo($namevar) = "some_random_name"
echo($nameval) = "Value to that random name"
Thanks.
well, you are using an Array, not an object. in order to get the array keys or values, you could use the following functions: array_values & array_keys.
i could add code snippets etc, but its really straight forward in php's docs:
http://php.net/manual/en/function.array-values.php
http://php.net/manual/en/function.array-keys.php
you could also possibly iterate the array or object (works the same for both), using something like the following code:
foreach($object as $key => $value) { ... }
you can use :
$myobject = [ 'key' => 'value' ];
$key = key($myobject);
$value = $myobject[$key];
echo $key; // key
echo $value; // value
it will return the key value for the current array element
see documentation
or you can use a foreach loop like this:
foreach($myobject as $key => $value) {
$namevar = $key;
$nameval = $value;
}
Basically you are asking how do we get the value of array objects? how do we use them?
These are array objects.
echo $yourObjectname->yourpropertyname;
in your case
echo $myobject->some_random_name;
Example -
$arr = Array (
[0] => stdClass Object (
[name] => 'abc'
);
echo $arr[0]->name;
Object is an instance of class or we can say an medium to use classes properties variable and methods.
I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.
I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.
This is the session:
$_SESSION['names']
I want to add a series of names to that array using array_push like this:
array_push($_SESSION['names'],$name);
I am getting this error:
array_push() [function.array-push]:
First argument should be an array
Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?
Yes, you can. But First argument should be an array.
So, you must do it this way
$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);
Personally I never use array_push as I see no sense in this function. And I just use
$_SESSION['names'][] = $name;
Try with
if (!isset($_SESSION['names'])) {
$_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
$_SESSION['total_elements']=array();
array_push($_SESSION['total_elements'], $_POST["username"]);
Yes! you can use array_push push to a session array and there are ways you can access them as per your requirement.
Basics:
array_push takes first two parameters array_push($your_array, 'VALUE_TO_INSERT');.
See: php manual for reference.
Example:
So first of all your session variable should be an array like:
$arr = array(
's_var1' => 'var1_value',
's_var2' => 'var2_value'); // dummy array
$_SESSION['step1'] = $arr; // session var "step1" now stores array value
Now you can use a foreach loop on $_SESSION['step1']
foreach($_SESSION['step1'] as $key=>$value) {
// code here
}
The benefit of this code is you can access any array value using the key name for eg:
echo $_SESSION[step1]['s_var1'] // output: var1_value
NOTE: You can also use indexed array for looping like
$arr = array('var1_value', 'var1_value', ....);
BONUS:
Suppose you are redirected to a different page
You can also insert a session variable in the same array you created. See;
// dummy variables names and values
$_SESSION['step2'] = array(
's_var3' => 'page2_var1_value',
's_var4' => 'page2_var2_value');
$_SESSION['step1step2'] = array_merge($_SESSION['step1'], $_SESSION['step2']);
// print the newly created array
echo "<pre>"; // for formatting printed array
var_dump($_SESSION['step1step2']);
echo "<pre>";
OUTPUT:
// values are as per my inputs [use for reference only]
array(4) {
["s_var1"]=>
string(7) "Testing"
["s_var2"]=>
int(4) "2124"
["s_var3"]=>
int(4) "2421"
["s_var4"]=>
string(4) "test"
}
*you can use foreach loop here as above OR get a single session var from the array of session variables.
eg:
echo $_SESSION[step1step2]['s_var1'];
OUTPUT:
Testing
Hope this helps!
Try this, it's going to work :
session_start();
if(!isset($_POST["submit"]))
{
$_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}
if(isset($_POST["submit"]))
{
$aa = $_POST['text1'];
array_push($_SESSION["abc"], $aa);
foreach($_SESSION["abc"] as $key => $val)
{
echo $val;
}
}
<?php
session_start();
$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');
array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);
foreach ($_SESSION['data'] as $eacharray)
{
while (list(, $value) = each ($eacharray))
{
echo "Value: $value<br>\n";
}
}
?>
output
Value: pappu Value: 10 Value: tippu Value: 12