push array key and value in associative array - php

I want to push array into existing session array. I would like to use get[id] and I want to be able stack all the arrays added rather than delete them when a new array is pushed.
Bellow is my code and I am not getting the value, instead I get this error --- Array to string conversion. Thanks in advance.
**CODE
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals']=array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo $key;
echo $value;
}
?>

With your code, this is what $_SESSION looks like:
array (size=1)
'animals' =>
array (size=1)
0 =>
array (size=1)
'id' => string 'test' (length=4)
In your code :
foreach($_SESSION['animals'] as $key=>$value)
key will contain 0 and value will contain array('id' => 'test'). Since value is an array, you cannot echo it like this.
If you want to echo all the characteristics of each animal, this code will work :
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals'] = array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
// We go through each animal
foreach($_SESSION['animals'] as $key=>$animal)
{
echo 'Animal n°'.$key;
// Inside each animal, go through each attibute
foreach ($animal as $attribute => $value)
{
echo $attribute;
echo $value;
}
}

Related

PHP multidimensional array not giving output

I've tried to display this information tons of times, i've looked all over stackoverflow and just can't find an answer, this isn't a duplicate question, none of the solutions on here work. I've a json array which is stored as a string in a database, when it's taken from the database it's put into an array using json_decode and looks like this
Array
(
[0] => Array
(
[0] => Array
(
)
[1] => Array
(
[CanViewAdminCP] => Array
(
[Type] => System
[Description] => Grants user access to view specific page
[Colour] => blue
)
)
)
)
However, when i try to loop through this, it just returns nothing, I've tried looping using keys, i've tried foreach loops, nothing is returning the values, I'm looking to get the Array key so "CanViewAdminCP" and then the values inside that key such as "Type" and "Description".
Please can anybody help? thankyou.
Use a recursive function to search for the target key CanViewAdminCP recursively, as follows:
function find_value_by_key($haystack, $target_key)
{
$return = false;
foreach ($haystack as $key => $value)
{
if ($key === $target_key) {
return $value;
}
if (is_array($value)) {
$return = find_value_by_key($value, $target_key);
}
}
return $return;
}
Example:
print_r(find_value_by_key($data, 'CanViewAdminCP'));
Array
(
[Type] => System
[Description] => Grants user access to view specific page
[Colour] => blue
)
Visit this link to test it.
You have a 4 level multidimensional array (an array containing an array containing an array containing an array), so you will need four nested loops if you want to iterate over all keys/values.
This will output "System" directly:
<?php echo $myArray[0][1]['CanViewAdminCP']['Type']; ?>
[0] fetches the first entry of the top level array
[1] fetches the second entry of that array
['CanViewAdminCP'] fetches that keyed value of the third level array
['Type'] then fetches that keyed value of the fourth level array
Try this nested loop to understand how nested arrays work:
foreach($myArray as $k1=>$v1){
echo "Key level 1: ".$k1."\n";
foreach($v1 as $k2=>$v2){
echo "Key level 2: ".$k2."\n";
foreach($v2 as $k3=>$v3){
echo "Key level 3: ".$k3."\n";
}
}
}
Please consider following code which will not continue after finding the first occurrence of the key, unlike in Tommassos answer.
<?php
$yourArray =
array(
array(
array(),
array(
'CanViewAdminCP' => array(
'Type' => 'System',
'Description' => 'Grants user access to view specific page',
'Colour' => 'blue'
)
),
array(),
array(),
array()
)
);
$total_cycles = 0;
$count = 0;
$found = 0;
function searchKeyInMultiArray($array, $key) {
global $count, $found, $total_cycles;
$total_cycles++;
$count++;
if( isset($array[$key]) ) {
$found = $count;
return $array[$key];
} else {
foreach($array as $elem) {
if(is_array($elem))
$return = searchKeyInMultiArray($elem, $key);
if(!is_null($return)) break;
}
}
$count--;
return $return;
}
$myDesiredArray = searchKeyInMultiArray($yourArray, 'CanViewAdminCP');
print_r($myDesiredArray);
echo "<br>found in depth ".$found." and traversed ".$total_cycles." arrays";
?>

how to set php internal pointer into an array back to the first element of the array?

I am getting some data stored on the array below,
<?php
$userData = Array
(
'j'=>21,
'temp' =>'Edwin',
'address'=> '1 Old Street',
'age' =>61
);
foreach($userData as $key => $value){
echo "{$key} => {$value}\n";
$index= $key;
}
?>
after i read the array with a foreach loop I want to keep the value of the first element in that array stored into a variable ?
To reset php's internal pointer into an array back to the first element, call the reset function.
in your case:
<?php
$userData = Array
(
'j'=>21,
'temp' =>'Edwin',
'address'=> '1 Old Street',
'age' =>61
);
foreach($userData as $key => $value){
echo "{$key} => {$value}\n";
$index= $key;
}
reset($userData); // Throw away return value
$item = reset($userData); //Keep first element of the array in $item.
echo $item;
?>
Note: Trying to echo the array echo $userData[0] will return u an Undefined offset

Check that variable is in an array

Possibly already been asked but I can't seem to find the answer I'm looking for.
How can I check that a variable is in an array?
Here is my code so far - ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
<?php if ($this->productOptions) { ?>
<?php foreach ($this->productOptions as $options) {
$array = $this->lastUpdatedProduct;
echo '<strong>' . $options['ProductID'] . '</strong>';
if(in_array($options['CentreID'], $array)) {
echo 'it exists';
}
}
}?>
Heres my array:
array
0 =>
array
'pid' => string '391' (length=3)
1 =>
array
'pid' => string '467' (length=3)
2 =>
array
'pid' => string '474' (length=3)
3 =>
array
'pid' => string '2985' (length=4)
4 =>
array
'pid' => string '2985' (length=4)
5 =>
array
'pid' => string '424' (length=3)
The problem is that $array is an array with arrays and you are trying to find something inside one of the inner arrays. Try with this:
foreach ($array as $entry) {
if (is_array($entry) && in_array($options['CentreID'], $entry))
echo 'it exists';
}
Ideally I wan't to echo out something when the ProductID is in the array
if(is_array($options['ProductID'])) { }
Live Preview
Edit
Ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
if(is_array($this->productOptions)) {
foreach($array as $pid) {
if(in_array($pid, $options['ProductID'])) {
//echo
}
}
}

How to extract array data in PHP variable with foreach?

I need to extract last array data i.e SiteName, Url, Title to the variable in php.
array
'ApplicableProductOfferings' =>
array
0 => string 'EasyDemo' (length=10)
'Artist' => string 'Hello' (length=10)
'ReferralDestinations' =>
array
0 =>
array
'SiteName' => string 'gettyimages' (length=11)
'Url' => string 'http://www.gettyimages.com/detail/160414706' (length=43)
'Title' => string 'Pixie Lott Launches The New BlackBerry Z10' (length=42)
'UrlComp' => string 'http://localhost.com' (length=197)
'UrlPreview' => string 'http://localhost.com' (length=164)
'UrlThumb' => string 'http://localhost.com' (length=82)
'UrlWatermarkComp' => string 'http://localhost.com' (length=197)
'UrlWatermarkPreview' => string 'http://localhost.com
try this.......
foreach($data as $dat)
{
foreach($dat['ReferralDestinations'] as $key => $d)
{
echo $d['SiteName'];
echo $d['Url'];
echo $d['Title'];
}
}
It depends on how you are storing the data in the array. If you have an array that already has the last array data, it's very simple.
foreach ($myArray as $var) {
echo $var;
}
or access individual elements as $myArray['SiteName'], $myArray['Url'] etc..
Assuming you have the above data in an array of arrays called $arrayOfArrays
foreach ($arrayOfArrays as $myArray) {
// $myArray now holds first array, second array etc as the loop is executed
// First time it holds 'ApplicableProductOfferings', second time 'ReferralDesinations'..
// If the array is 'ReferralDesitnations' you can loop through that array
// to get the elements you are looking for SiteName etc as below
foreach ($myArray as $URLElement) {
echo $URLElement;
}
}
$array1 = [];
$array2 = [];
foreach ($array1 as $key=> $val) {
extract($array2, EXTR_IF_EXISTS, $val);
}
// extract() flags => EXTR_IF_EXISTS ...
// http://php.net/manual/ru/function.extract.php

Different way to convert object to array using PHP

When use this code:
$array=(array)$yourObject;
The properties of $yourObject convert to index an array, but how can convert as one array, these means, the $yourObject be one index of $array and I echo $array[0] for access through object?!
Another way for question, please see this sample code:
<?php
$var1 = (string) 'a text';
$var2 = (array) array('foo', 'bar');
$var3 = (object) array("foo" => 1, "bar" => 2);
//It's OK.
foreach((array)$var1 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's OK.
foreach((array)$var2 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's NOT OK. I want through $var3 in output as an array with one index!
foreach((array)$var3 as $v) {
echo $v."<br>";
}
echo "<hr>";
?>
Other way:
I want use a variable in foreach but I not sure about type this, I want working foreach without error for any type variable (string, array, object,...)
For example I thinks must I have this sample output for some this types:
Output for $var1:
array
0 => string 'a text' (length=6)
Output for $var2:
array
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
Output for $var3:
array
0 =>
object(stdClass)[1]
public 'foo' => int 1
public 'bar' => int 2
And the end I sure the foreach return current result without error.
You mean to wrap your object inside an array?
$array = array($yourObject);
As mentioned by mc10, you can use the new short array syntax as of PHP 5.4:
$array = [$yourObject];

Categories