Anything to attend when changing values in a multidimensional foreach() loop? - php

I got a site that executes the following code
$keywords = ($_SESSION[$_POST['ts']]);
print_r($keywords);
foreach ($keywords as $keyword) {
foreach ($keyword['whitelist'] as $entry) {
foreach ($_POST as $key => $value) {
if ($key == $entry['encoded_url']) {
$entry['ignore'] = $value;
$decodedURL = $this->base64->url_decode($entry['encoded_url']);
if ($value == 'noignore') {
echo "found!<br />";
$this->blacklist_model->remove($decodedURL);
$html = $this->analyse->getHTML($decodedURL);
$entry['html'] = $html[0];
$entry['loading_time'] = $html[1];
}
if($value == 'alwaysignore') {
$this->blacklist_model->add($decodedURL);
}
}
}
}
}
print_r($keywords);
The output looks like this:
http://pastebin.com/B3PtrqjB
So, as you see, there are several "found!"s in the output, so the if clause actually gets executed a few times and I expected the second array to contain new data like 'html', but, as you see, nothing changes. Is there anything to attend when changing values in multidimensional foreach() loops?

foreach creates a copy of the array and loops through that. Modifying values doesn't work.
You can get around this, though, by using references.
foreach ($keywords as &$keyword) {
foreach ($keyword['whitelist'] as &$entry) {
foreach ($_POST as $key => &$value) {
...
}
}
}
With that you can modify $value and it WILL affect the original array.

You suppose to change the Original array.
$entry is just an instance / unconnected node.
you need to change $keywords, and not its on the fly created nodes.

Related

Modify array during multiple foreach loop iterations

I've to update data for array which has 4 foreach loops,
foreach ($dta['hotels']['hotels'] as $key => &$value) {
foreach ($value['rooms'] as $key1 => $value1) {
foreach ($value1['rates'] as $key2 => $value2) {
foreach ($value2['shiftRates'] as $key3 => &$value3) {
$value3['net'] = 0.000072*$value3['net'];
$value3['sellingRate'] = 0.000072*$value3['sellingRate'];
var_dump($value3['sellingRate']);
}
}
}
$value['currency'] = 'USD';
}
I want to update data of very deep 4th foreach loop, which isn't updating data, where as first loop data update was possible.
i've tried to put "&" but in first loop it worked and in 4th loop it's not working.
Any possible solutions ?
You have all keys, you can use these to modify your values :
$dta['hotels']['hotels'][$key]['rooms'][$key1]['rates'][$key2]['shiftRates'][$key3]['sellingRate'] = 0.000072 * $value3['sellingRate'];
As long as there are no other net or sellingRate keys somewhere else in the array that you don't want to modify, you can do this more simply with array_walk_recursive.
array_walk_recursive($dta, function(&$value, $key) {
if ($key === 'net' || $key === 'sellingRate') {
$value *= 0.000072;
}
});

foreach leaves out the very first value

I am processing a foreach(first) which gives the full array in the data, when I make another foreach(second) and pass the first foreach into second foreach the first value of the first foreach never appears in the second foreach. Does anyone have any idea why the foreach behaves this way? is there a solution for this?
I tried it this way no luck
$userIdsPerRoom = chatRoomUsersId($_SESSION['currentRoomID']);
foreach ($userIdsPerRoom as $value) {
$list[] =$value['UserID'];
}
foreach ($list as $value) {
$userInfo = chatRoomUsersEmail($value);
foreach ($userInfo as $info) {
echo $info['userEmail'];
}
}
echo count($list); ///gives the full list
}
I noticed it with this code
$userIdsPerRoom = chatRoomUsersId($_SESSION['currentRoomID']); //return an array of intergers with five values example array(1,2,3,4,5)
foreach ($userIdsPerRoom as $value){
$userInfo = chatRoomUsersEmail($value['UserID']);
foreach ($userInfo as $info){
echo $info['userEmail']; /// I only get four values example array(b,c,d,e)
}
}

PHP Nested loops where values are the key to the next level of the array

I'm relatively new to PHP and I hope you can help me solve my problem. I am selecting out data from a database into an array for timekeeping. Ultimately, I would like to calculate the total number of hours spent on a project for a given customer.
Here is the code to populate a multi-dimensional array:
...
foreach ($record as $data) {
$mArray = array();
$name = $data['user'];
$customer = $data['customer'];
$project = $data['project'];
$hours = $data['hours'];
$mArray[$name][$customer][$project] += $hours;
}
...
I would now like to iterate over $mArray to generate an xml file like this:
...
foreach ($mArray as $username) {
foreach ($mArray[$username] as $customerName) {
foreach ($mArray[$username][$customerName] as $project ) {
echo '<'.$username.'><'.$customerName.'><'.$project.'><hours>'.
$mArray[$username][$customerName][$project].'</hours></'.$project.'>
</'.$customerName.'></'.$username.'>';
}
}
}
This nested foreach doesn't work. Can someone give me a couple of tips on how to traverse this structure? Thank you for reading!
UPDATE:
Based on the comments I've received so far (and THANK YOU TO ALL), I have:
foreach ($mArray as $userKey => $username) {
foreach ($mArray[$userKey] as $customerKey => $customerName) {
foreach ($mArray[$userKey][$customerKey] as $projectKey => $projectName) {
echo '<name>'.$userKey.'</name>';
echo "\n";
echo '<customerName>'.$customerKey.'</customerName>';
echo "\n";
echo '<projectName>'.$projectKey.'</projectName>';
echo "\n";
echo '<hours>'.$mArray[$userKey][$customerKey][$projectKey].'</hours>';
echo "\n";
}
}
}
This is now only providing a single iteration (one row of data).
Foreach syntax is foreach($array as $value). You're trying to use those values as array keys, but they're not values - they're the child arrays. What you want is either:
foreach($mArray as $username) {
foreach($username as ...)
or
foreach($mArray as $key => $user) {
foreach($mArray[$key] as ...)

Getting certain array from a multidimensional array

I have multidimensional array which is a query returning the info from a table named 'users'. In another part of my code I need to get the records of only one certain user and I want to take it using the array I mentioned above. It's of type:
This is probably what you're looking for:
$row = NULL;
foreach ($parent as $key => $child)
{
if (1 == $child['id'])
{
$row = $child; break;
}
}
if (isset($row))
{
// Stuff to do with the chosen row
}
$main = // your array
foreach ($main as $index => $sub) {
foreach ($sub as $subIndex => $item) {
if ($item['id'] == xxx) {
return $main[$index][$subIndex];
}
}
}
IMO using for loops (rather that foreach) would make it easier for you to reference the variable you need (by using the for loop variable to look up the appropriate row in the array)
HTH,
David

How to foreach through part of an objects member variables that are arrays?

I am trying to create a foreach that will go through some variables within an object.
At the moment it is just
class jabroni
{
var $name = "The Rock";
var $phrases = array ("The rock says", "Im gonna put the smackdown on you", "Bring it on jabroni");
var $moves = array ("Clothes line", "Pile driver", "Reverse flip");
}
I tried doing this:
$jabroni = new jabroni()
foreach ($jabroni as $value)
{
echo $value->phrases;
echo $value->moves;
}
However nothing gets printed.
Any ideas if what I am trying to achieve is possible, I have that gut feeling that its not and that I will have to just do individual foreach statements for each object member variable that is an area?
Thanks for your time!
You are doing wrong the loop.. You have one object, not an array of objects. so the correct way should be..
$jabroni = new jabroni();
foreach ($jabroni->phrases as $value)
{
echo $value;
}
foreach ($jabroni->moves as $value)
{
echo $value;
}
foreach ($jabroni->phrases as $value) {
echo $value;
}
foreach ($jabroni->moves as $value) {
echo $value;
}
You can do it in nested foreach loops. This will be easy instead of going for two for loops seperatley
foreach ($jabroni as $keys => $values)
{
if ($keys == 'phrases' || $keys == 'moves') {
foreach ($values as $value) {
echo $value;
}
}
}

Categories