how to use foreach with array_key_exists function - php

I am trying to loop around an array of return values from a 'POST form' and to then place those values into a database.
the problem that I have is to determine the best way to loop around those values. I tried using the array_key_exists(). but it appears that this function only works with an If clause.
I am working in ZendFrameWork 1.
I enclose my code below and would really appreciate any help and advice.
foreach(array_key_exists('id', $ReturnedPostvalues))
$product = EP3D::getSource('EP3D/Products')->retrieve($productId);
{
$product->quantity = $ReturnedPostvalues['quantity'];
$product->price = $ReturnedPostvalues['price'];
$product->rrp = $ReturnedPostvalues['rrp'];
$product->save();
}
}
the var_dumped array values returned from the post
array(6) {
["quantity"]=>
string(3) "222"
["price"]=>
string(3) "220"
["rrp"]=>
string(2) "22"
["sampleId"]=>
string(5) "42960"
["id"]=>
string(1) "5"
["delete"]=>
string(1) "0"
}
[6]=>
array(7) {
["quantity"]=>
string(4) "7777"
["price"]=>
string(4) "2022"
["rrp"]=>
string(2) "22"
["sampleId"]=>
string(5) "42960"
["id"]=>
string(1) "6"
["delete"]=>
string(1) "0"
}
I basically need to loop around this array and input the data into the database.

Maybe this is what you want:
foreach($ReturnedPostvalues as $value) {
if (array_key_exists('id', $value)) {
$product = EP3D::getSource('EP3D/Products')->retrieve($value['id']);
$product->quantity = $value['quantity'];
$product->price = $value['price'];
$product->rrp = $value['rrp'];
$product->save();
}
}
You need to refresh your understanding of multi-dimensional arrays. Your problem is that you seemed to confuse accessing the top-level array and accessing the sub-arrays.

Related

How can I get the value of a key in this associative array

I have a CMS I am using that serializes their data in the database. I used the unserialize() function to convert the data into an associative array. Now I am having a hard time pulling the value of the image from the associative array:
This is the simple while loop I am using to loop through the rows:
while($row = mysql_fetch_assoc($query_models)){
$model_name = $row['ModelName'];
$model_thumbnail = unserialize($row['info']);
}
this is the Key and Value of the array I need to get the value of, so I can assign the correct thumbnail image to the respected person:
["1x_filename"]=> string(19) "00/83/83-set-1x.jpg"
The full array is below, and the key I am targeting is located more at the bottom of this array:
array(1) {
["thumbs"]=> array(2) {
[16]=> array(17) {
["id"]=> string(2) "82"
["1x_width"]=> string(3) "220"
["1x_height"]=> string(3) "330"
["2x_width"]=> string(3) "440"
["2x_height"]=> string(3) "660"
["3x_width"]=> string(3) "660"
["3x_height"]=> string(3) "990"
["4x_width"]=> string(3) "880"
["4x_height"]=> string(4) "1320"
["width"]=> string(3) "220"
["height"]=> string(3) "330"
["retinamode"]=> string(1) "1"
["filename"]=> string(10) "82-set.jpg"
["1x_filename"]=> string(19) "00/82/82-set-1x.jpg"
["2x_filename"]=> string(19) "00/82/82-set-2x.jpg"
["3x_filename"]=> string(19) "00/82/82-set-3x.jpg"
["4x_filename"]=> string(19) "00/82/82-set-4x.jpg"
}
[17]=> array(17) {
["id"]=> string(2) "83"
["1x_width"]=> string(3) "106"
["1x_height"]=> string(3) "150"
["2x_width"]=> string(3) "212"
["2x_height"]=> string(3) "300"
["3x_width"]=> string(3) "318"
["3x_height"]=> string(3) "450"
["4x_width"]=> string(3) "424"
["4x_height"]=> string(3) "600"
["width"]=> string(3) "106"
["height"]=> string(3) "150"
["retinamode"]=> string(1) "1"
["filename"]=> string(10) "83-set.jpg"
["1x_filename"]=> string(19) "00/83/83-set-1x.jpg"
["2x_filename"]=> string(19) "00/83/83-set-2x.jpg"
["3x_filename"]=> string(19) "00/83/83-set-3x.jpg"
["4x_filename"]=> string(19) "00/83/83-set-4x.jpg"
}
}
}
Any help would be greatly appreciated. Thanks!
Just like this :
$model_thumbnail = unserialize($row['info']);
$picturePath = $model_thumbnail['thumbs'][17]['1x_filename'];
picturePath will contain your images path
I would recommend you to use mysqli or an other database adapter in php, as mysql_ functions are depricated and even removed in never php versions. But according to your code, you could simply use a foreach loop to get your data.
Your results gives back some kind of data groups, I assume those are the user ids or something similar. It could also be the version or something like it. As I do not know that here are two possible ways
Get all:
while($row = mysql_fetch_assoc($query_models)){
$model_name = $row['ModelName'];
$model_thumbnail = unserialize($row['info']);
// echo all 1x_filename values from all given "ids"
foreach ($model_thumbnail['thumbs'] as $model_id => $model_values) {
print $model_values['1x_filename'];
}
}
Get only the latest id, in case those are for some kind of versioning:
while($row = mysql_fetch_assoc($query_models)){
$model_name = $row['ModelName'];
$model_thumbnail = unserialize($row['info']);
// sort array, so highest ID (assume-ably the newest)
krsort($model_thumbnail['thumbs']);
// get array entry
$firstEntry = reset($model_thumbnail['thumbs']);
print $firstEntry['1x_filename'];
}

Create nested pages-list from MySQL database using recursion with fixed ordering

I am trying to create a nested pages-list from data stored in the MySQL database.
I try to do this because users can order the pages (using JS-script nestedSortable) in the way they want and from that array, I can then create a menu with the items in the right order.
My pages have the following data stored:
page_id
parent_page_id
ordering
site_id
title
I retrieve the following from the database:
SELECT * FROM `pages` WHERE site_id = '".$iSite_id."' ORDER BY parent_page_id, ordering ASC;
If a page does not have a parent, the parent_page_id is 0.
So far so good, but I have a lot of problems understanding how a recursive function works, and because the amount of levels is (theoretically) endless, I can't work around creating this function.
This is what I have so far:
$aPagesMenu = $oPage_controller->return_pages_menu($iSite_id);
function create_menu_recursive($aPagesMenu) {
foreach($aPagesMenu as $aPage) {
if($aPage['parent_page_id']){
$aMenu[$aPage['parent_page_id']][$aPage['page_id']] = $aPage['title'];
//Recursive function call here?
} else {
$aMenu[$aPage['page_id']] = $aPage['title'];
}
return $aMenu;
}
$aRecursiveMenu = create_menu_recursive($aPagesMenu);
I get stuck at trying to understand how the recursive function returns its content into the array of the first level?
How can I understand this and correctly nest one level into another?
I really wish to understand this, because it gives me a lot of delay and issues. Any help is welcome!
EDIT
Some data retreived from database:
array(6) {
[0]=>
array(4) {
["page_id"]=>
string(3) "274"
["parent_page_id"]=>
string(1) "0"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[1]=>
array(4) {
["page_id"]=>
string(3) "278"
["parent_page_id"]=>
string(1) "0"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
[2]=>
array(4) {
["page_id"]=>
string(3) "273"
["parent_page_id"]=>
string(3) "274"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[3]=>
array(4) {
["page_id"]=>
string(3) "275"
["parent_page_id"]=>
string(3) "274"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
[4]=>
array(4) {
["page_id"]=>
string(3) "276"
["parent_page_id"]=>
string(3) "275"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[5]=>
array(4) {
["page_id"]=>
string(3) "277"
["parent_page_id"]=>
string(3) "275"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
}
This data should then be converted to:
273
--> 275
--> 274
--> 276
--> 277
278
etc..
I have searched through older posts on stackoverflow and I think I have found what I was looking for: PHP Building Recursive Array from List
I have used the following code as recursive function:
private function buildTree($itemList, $parentId) {
// return an array of items with parent = $parentId
$result = array();
foreach ($itemList as $item) {
if ($item['parent_page_id'] == $parentId) {
$newItem = $item;
$newItem['children'] = $this->buildTree($itemList, $newItem['page_id']);
$result[] = $newItem;
}
}
if (count($result) > 0) return $result;
return null;
}
I then called this function with the array I've got from the database:
buildTree($aPages, 0);
Which gave me the array :D

PHP CodeIgniter Foreach Returning Incorrect Data

Hello awesome programmers!
I am so sorry for the the novice question, however, I am having trouble finding a solution to my problem. I am attempting to run a for each loop through my array passed from my controller, however, the data being outputted is not the same as when I run a var_dump($array). I am thinking perhaps that I need to iterate through this object maybe? However, when I attempt to do so, I get a non-object error.
Controller:
$data['user_details'] = $this->ion_auth->user()->row();
View:
var_dump($user_details);
foreach($user_details as $item){
echo $item['email'];
}
The output of this is : "21nfn4111NR12" but should be roger#peterson.net!
I have also tried the object form:
var_dump($user_details);
foreach($user_details as $item){
echo $item->email;
}
However, it results in error trying to get property of non-object!
When I run the var dump I get the following:
object(stdClass)#21 (17) {
["id"]=>
string(1) "2"
["ip_address"]=>
string(14) "119.132.127.01"
["username"]=>
string(12) "roger petereson"
["password"]=>
string(40) "fdZxF/RQo4nZKmbA5XQlwefbc8f8e5c74899c3d0"
["salt"]=>
NULL
["email"]=>
string(19) "roger#peterson.net"
["activation_code"]=>
NULL
["forgotten_password_code"]=>
NULL
["forgotten_password_time"]=>
NULL
["remember_code"]=>
string(22) "44hjOlloLTIrkSrjSBVNie"
["created_on"]=>
string(10) "1404939094"
["last_login"]=>
string(10) "1405099607"
["active"]=>
string(1) "1"
["first_name"]=>
string(6) "Roger"
["last_name"]=>
string(5) "Peterson"
["is_owner"]=>
string(1) "1"
["user_id"]=>
string(1) "2"
}
The following line:
$this->ion_auth->user()->row();
returns an object not an array (check your var_dump output), so you just need to
echo $user_details->email;

How to get last value from this array?

How to get the last array value of this var_dump?
I do a var_dump on a variable ($submission) and get this:
object(stdClass)#148 (8) {
["sid"]=> string(3) "199"
["nid"]=> string(4) "3042"
["submitted"]=> string(10) "1386113448"
["remote_addr"]=> string(9) "127.0.0.1"
["uid"]=> string(2) "21"
["name"]=> string(8) "SClosson"
["is_draft"]=> string(1) "0"
["data"]=> array(1) {
[1]=> array(1) {
[0]=> string(8) "blahblah"
}
}
}
So I need to store blahblah in a variable from the above array, but how?
Thought I could just get it by doing this: $submission['data'][1][0], but that doesn't work. How do I return blahblah from this?
If you need an array, you can type cast it
$result = (array) $submission;
Or as an object, access the data as public properties
echo $submission->data[1][0];
You can use array_pop if you want to get the last value of an array.
http://www.php.net/manual/en/function.array-pop.php

PHP Retrieving data values from foreach on sub arrays

I'm trying to get the values of a sub array out in a foreach loop.
I looked at this example as it seemed really relevant to my problem, but unfortunately I've not been able to get it to work, and I'm hoping someone here can pick up where I've gone wrong.
PHP foreach not working with sub-array
I have an array called $booked and inside that array I have a sub array $booked['30_booked'].
Within that second array there are multiple values, such as title, name, address etc.
My code currently looks like this:
foreach($booked['30_booking'] as $new_var){
var_dump('</br>', $booked['30_booking']);
var_dump('</br>', $new_var);
var_dump($new_var['title'], $new_var->title, $booked['30_booking']->title); exit();
}
I've output the data as you can see above in var_dump statements to try and get one of these methods to work.
Unfortunately nothing within $new_var is pulling out the title, but $booked['30_booking']->title
Have I not put it into the foreach statement correctly?
All help appreciated - thanks!
EDIT:
Main array output snippet:
array(6) { ["30_booked"]=> object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" } }
EDIT 2:
Sub Array $booked['30_booking'] snippet:
object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" }
EDIT 3:
My var_dump of the $new_var by itself is bringing back the value of the id - but when I try and get the second value out the sub array "title" it doesn't return anything.
FINAL FIX:
Thanks to Kita I realised I was returning a std class object and not a second array, something that I stupidly missed the first time round. Because of that I can't actually foreach on the object.
Which led me to this post which will help me fix the issue:
PHP foreach array with stdClass Object
Thank you very much for all your help!!!
You expected an array inside $booked['30_booking'] but in fact there was a stdClass object.
array(6) {
["30_booked"]=> object(stdClass)#21 (34) {
["id"]=> string(2) "30"
["title"]=> string(2) "Ms"
["firstname"]=> string(5) "FIRST NAME"
["surname"]=> string(9) "LAST NAME"
["address"]=> string(6) "- -- -"
["postcode"]=> string(7) "FAK E99"
["country"]=> string(14) "United Kingdom"
["phone"]=> string(11) "01221111111"
["alt_phone"]=> string(0) ""
["email"]=> string(25) "fake#fake.co.uk"
["notes"]=> string(8) "FAKE DEAL"
}
//I assume you have left out the other array elements from the Main array snippet.
}
Getting stdClass instead of array usually happens when you parse a JSON string with json_decode() without the second parameter.
// without second parameter
var_dump( json_decode( '{"id":"30"}' ) );
object(stdClass)#1 (1) {
["id"]=>
string(2) "30"
}
// 'true' as second parameter
var_dump( json_decode( '{"id":"30"}', true ) );
array(1) {
["id"]=>
string(2) "30"
}
Above examples are hosted at: http://ideone.com/GNMRlD
Since stdClass object itself does not provide iteration functionality, using it with foreach will yield errors.
You can convert stdClass into array with functions such as http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/ .
For eg. if your array looks like below. foreach which I used will be working
$new_array = array(array('total'=>array('title'=>'test','text'=>'text')));
foreach ($new_array as $val)
{
print_r($val['total']['title']); // Use this for array
print_r($val->total->title); // Use this for object
}
if your array looks like below. Use the below foreach.
$new_array = array(array('total'=>array(array('title'=>'test','text'=>'text'),array('title'=>'test1','text'=>'text1'))));
foreach ($new_array as $val)
{
foreach($val['total'] as $new_val)
{
print_r($new_val['title']);
}
}
You can try this, I hope that helps you
foreach($booked as $new_var){
var_dump('</br>', $new_var);
var_dump('</br>',$new_var['30_booking']->title);
}
I think in your foreach there is mistake of word 30_booking
since in your main array out put display it shows 30_booked
check that also

Categories