accessing values from php array - php

I have been having an issue getting values out of an array that is formatted like so:
array(
[key]=>array(
[0]=>value
[1]=>value
[2]=>value)
[key]=>array(
[0]=>value
[1]=>value))
I am using a queue to run through each key as the queue item and process the information. so to create the queue item I have tried this:
while ($array = $result->fetchAssoc())
{
$queue->createItem($array);
}
this fails to create any items so I have used this method instead
if ($array != 0 || $array != NULL) {
foreach ($array as $row) {
$queue->createItem($row);
}
}
Once the queue item is created the queue calls a function passing the queue $item and here is where I have problems as I can successfully get all the values of the second level array but I can not access the Key of the first level.
function work_function($item){
foreach($item as $row=>$job){
//do something
}
}
In my function I have tried:
//1
$arrayKEY= $item;
//2
foreach($item as $row){
$arrayKEY= $row;
}
I just cannot get the values I need. What am I doing wrong/can I do to accomplish this?
Thanks

There's not much info here, but if the array is like you show, it's a multi-dimensional array, and thus needs 2 for loops.
function work_function($item){
foreach($item as $row=>$job){
echo "Row $row:\n";
foreach($job as $value){
echo $value."\n";
}
}
}

Related

PHP Array Values same element in different formats and posting from div data

I have a foreach loop for an array
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
$total += $something['Cost'];
$singleprice = $available['Cost'];
}
I need to be able to return $total and $singleprice - Total adding up all the values within the key, $singleprice returning only 1 instead of all added up
The only way I've managed to return this value is by creating another foreach loop within this foreach loop like so:
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
foreach($somethings as $key3 => $singlesomething)
{
$singleprice = $singlesomething['Cost'];
}
$total += $something['Cost'];
}
Why will the above first method return nothing? I then use this variable which now has the data in a Div Data- (data-single-cost="'.$singleprice.'" ) which is then used to POST a form
$singleprice = $_POST['single-cost'];
Yet it returns 0 even with the second method successfully getting the value
any ideas what I'm doing wrong?
I guess its because somehow program goes into the if and you have unset available in it, so singleprice gots nothing.
Maybe you should get a Xdebug and try some step debug to see what happend.

Bug when trying to update an array

I have a two questions with a symfony's project.
My first one :
I am trying to modify some data in an array.
I have this code
var_dump($results); // FIRST ONE
foreach ($results as $result) {
foreach ($result as $res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
var_dump($res); // THIS ONE IS MODIFIED
}
}
var_dump($results); // LAST ONE... SAME AS THE FIRST ONE
I don't understand why my array ' $results ' is no updated... am i missing something ?
And my second question : is there any way to simplify this code ? I don't like the 3 foreach.
Thanks you guys :)
PHP foreach copy each item when iterate so $result array will not update when you change $res item.
1) You can use array keys to change main array
foreach($arrr as $k => $item) {arrr[$k]['key'] = 'changed'}
2) Or you can get link to the $res item and change it dirrectly
foreach($arrr as &$item) {$item['key'] = 'changed'}
Note that second case can cause different issues
Unless you're passing an object in PHP, PHP does not pass values by reference. $res is a copy of the value, not a link to the original value. If you know what you're doing, you can pass by reference. When passing by reference, altering $res would alter the original data. You pass by reference by prefixing a & to the variable or argument.
Since this is a nested foreach, you'll also have to pass $result by reference to avoid that being a copy of the item of $results.
foreach ($results as &$result) {
foreach ($result as &$res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
}
}

(Why) should I test if an array is empty prior to a for loop?

Given an empty array $items = array();
Why should I use the following code (which I've seen used before):
if (count($items) > 0) {
foreach ($items as $item) // do stuff here
}
instead of just
foreach ($items as $item) // do stuff here
If count($items) === 0 the loop won't execute anyway??
You don't generally need to do the check. I see lots of code with that check, but it's often unnecessary, and I think it's usually due to ignorance on the part of the programmer. A similar pattern that I frequently see is after database queries:
if (mysqli_num_rows($stmt) > 0) {
while ($row = mysqli_fetch_assoc($stmt)) {
...
}
}
This test is also unnecessary; if no rows were found, the first fetch will return false, and the loop will stop.
The only case where it's useful is if you want to tell the user that there were no results, instead of just displaying an empty table. So you might do:
if (count($items) > 0) {
echo "<table>";
foreach ($items as $item) {
// display table row
}
echo "</table>";
} else {
echo "<b>No data found!</b>";
}
It actually depends on what you want to do. As the comments have pointed out, you may want an empty array to be a special case, so you'd like to handle that case differently. Otherwise, no warning will be thrown if you execute foreach on an empty array, you just won't get any results. A typical check you should execute is if $items is an array at all, or cast $items into an array anyway to avoid getting that warning. If you did that and $items would be generally be converted into an array of one value, i.e. the value $items had at that point.
e.g.
$items = 2;
foreach((array)$items as $item) {
print $item; //will print 2 alright
}
or
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
else {
// do something here
}

how to add another attribute using foreach loop to an array of rows

I am using a foreach loop on an array of rows in a model file in CodeIgniter.
What i want to do is reflect the changes i make in every row ,in the foreach loop ,to the original array.
$unique = $this->db->get_where('list', array('item_index' => $item));
foreach ($unique->result_array() as $row)
{
$row["status"]= "Not Unique";
if($row["bid_amount"]==$amount)
{
if($count==0){ $row["status"]="Unique and Final"; }
else {$row["status"]="Unique but Not Final"; }
}
$count++;
}
return $unique;
I am adding another attribute to each row here and i want to echo this attribute corresponding to each row in a view file.
But i am getting error Undefined index: status.
How can i possibly reflect the changes in the array to be returned.
Assign the result_array() to a variable, iterate over it, but change the original array and not the local one. PHP's foreach comes in two flavours:
foreach($arr as $value) and foreach($arr as $key => $value)
Try this:
$results = $unique->result_array();
foreach ($results as $rK => $rV){
$results[$rK]["status"]= "Not Unique";
//other stuff.
}
return $results;
Alternatively, you can pass by reference:
foreach ($results as &$result) {
$result['status'] = "Not Unique";
}
See the PHP docs on arrays. Specifically Example 10.
In your foreach the $row refers to a variable that's local to the loop. Thus changing it does not affect the data in $unique.

How to get at the value of a specific array ID

I have an array called $fields. If I do this:
foreach ($fields as $id => $field) {
print $id."<br />";
}
I get:
field_track_icon
field_session_number
field_job_title
I know this is totally simple, but my brain just will not come up with the answer, and I can't seem to google the right terms. How can I wrap the foreach in an if statement that's based on which id is being processed?
Pseudocode would be:
if($fields['field_session_number'] == 'S2') {
foreach($fields as $id=>$field) {
print $field->content;
}
}
Basically, I'm working with a single record of data returned in the $fields array. I only want to print out the individual field properties ($field->content or $field->prefix, for example) if the id of the field being processed is S2.
If you want to get element with specific key, you don't have to make for cycle - you just get it.
$field = $fields['field_session_number'];
echo $field->content;
echo $field->prefix;
If ID is not array key, but same as content or prefix, then you need for cycle:
foreach ($fields as $field) {
if ($field->id === 'S2') {
echo $field->content;
}
}

Categories