Replace values in two dimensional associative array - php

$update is a two dimensional associative array. Part of the var_dump is:
array(101) {
[0]=> array(27) { ["code"]=> string(4) "2014" ["na1"]=> string(4) "6010" and many more fields following }
[1]=> array(27) { ["code"]=> string(4) "2015" ["na1"]=> string(4) "6010" and many more fields following }
and many more subarrays following of course . . .
Need to replace the code value with a name and created:
foreach($update as $key=>$subarray){;
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
$val="Name1";
}
elseif ($key=='code' && $val==2015)
{
$val="Name2";
}
}
}
var_dump($update);
The echo $subkey and $val give perfectly the correct values, however de If statement seems never to be true (or is cancelled out again somehow) as the var_dump is leading again to the original values
Some Stackoverflow research even showed constructions with only one foreach loop, much more elegant, but seems not to reach the second array level.
Is there a better approach? Solution to fix this one?

You are not updating the source array.
foreach($update as $key=>$subarray){
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
//$val="Name1";
$update[$key][$subkey] = "Name1" ;
}
elseif ($key=='code' && $val==2015)
{
//$val="Name2";
$update[$key][$subkey] = "Name2" ;
}
}
}

You can access to the field you want by index.
Example :
$i = 0;
$j = 0;
foreach($update as $key=>$subarray){;
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
$update[$i][$j] = "Name1";
}
elseif ($key=='code' && $val==2015)
{
$update[$i][$j] = "Name2";
}
$j++
}
$j = 0;
$i++;
}
var_dump($update);

$newArr = array();
foreach($update as $key=>$subarray){
$subNewArr = array();
foreach ($subarray as $item) {
if ($item['code']==2014)
{
$item['code']="Name1";
}
elseif ($item['code']==2015)
{
$item['code']="Name2";
}
array_push($subNewArr, $item);
}
array_push($newArr, $subNewArr);
}
var_dump($update);
Less if else checking

Related

PHP arrray and string

I have problems with arrays. When I try to get the first array [0] it does not give me anything.
This is output
array(4) { [0]=> string(0) "" [333]=> string(123) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/f/de/d6/fded6f1587f863a9e8fc1c2173143a8782fa655e/700Wx700H-105395-0416.jpg" [334]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/e/b9/54/eb954216442547d2ed2c71adbcf73d4f2b3ef903/700Wx700H-105395-a-0416.jpg" [335]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/7/16/95/71695917dd17d29648c8f4907000e3c6cab64581/700Wx700H-105395-b-0416.jpg" }
and this is code
private function getImages($dom) {
$images = [];
foreach ($dom->getElementsByTagName('ul') as $ul) {
if ($ul->getAttribute('class') == 'image-thumbnails') {
foreach ($dom->getElementsByTagName('li') as $li) {
$images[] = $li->getAttribute('data-zoom-url');
}
}
}
$images = array_unique($images);
return $images;
}
If you want to exclude empty values, check if the attribute is empty before adding it to the array:
if(!empty($li->getAttribute('data-zoom-url'))) {
$images[] = $li->getAttribute('data-zoom-url');
}

php loop through array

I am trying to get certain values from an array but got stuck. Here is how the array looks:
array(2) {
[0]=>
array(2) {
["attribute_code"]=>
string(12) "manufacturer"
["attribute_value"]=>
string(3) "205"
}
[1]=>
array(2) {
["attribute_code"]=>
string(10) "silhouette"
["attribute_value"]=>
array(1) {
[0]=>
string(3) "169"
}
}
}
So from it I would like to have attribute_values, and insert it into a new array, so in this example I need 205 and 169. But the problem is that attribute_value can be array or string. This is what I have right now but it only gets me the first value - 205.
foreach ($array as $k => $v) {
$vMine[] = $v['attribute_value'];
}
What I am missing here?
Thank you!
If sometimes, attribute_value can be an array, and inside it the values, you can just check inside the loop (Provided this is the max level) using is_array() function. Example:
$vMine = array();
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) { // check if its an array
// if yes merge their contents
$vMine = array_merge($vMine, $v['attribute_value']);
} else {
$vMine[] = $v['attribute_value']; // if just a string, then just push it
}
}
I suggest you to use array_map instead of for loop. You can try something like this..
$vMine = array_map(function($v) {
return is_array($v['attribute_value']) ? current($v['attribute_value']) : $v['attribute_value'];
}, $arr);
print '<pre>';
print_r($vMine);
Try the shorthand version:
foreach ($array as $k => $v) {
$vMine[] = is_array($v['attribute_value']) ? current($v['attribute_value']):$v['attribute_value'];
}
or the longer easier to understand version, both is the same:
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) {
$vMine[] = current($v['attribute_value']);
} else {
$vMine[] = $v['attribute_value'];
}
}

how to unset the item in $_SESSION array

i have 2 functions. First one is adding item to cart, second should delete specific item based on product id.
function AddToCart($pid) {
if (isset($_SESSION['products']['prod_count'])) {
$_SESSION['products']['prod_count'] ++;
$incart = $_SESSION['products']['prod_count'];
$_SESSION['products'][$incart]['product_id'] = $pid;
} else {
$_SESSION['products']['prod_count'] = 0;
$incart = $_SESSION['products']['prod_count'];
$_SESSION['products'][$incart]['product_id'] = $pid;
}
}
function DeleteProduct($pid) {
foreach ($_SESSION['products'] as $key => $my_value) {
foreach ($my_value as $key => $product_id) {
if ($product_id == $pid) {
// do not know how to unset this product
}
}
}
}
I need some idea on how to unset the product if $product_id == $pid or may be some other ideas how to achieve that.
My array look something like:
array(1) { ["products"]=> &array(4)
{ ["prod_count"]=> int(2)
[0]=> array(1) { ["product_id"]=> int(4)}
[1]=> array(1) { ["product_id"]=> int(10) }
[2]=> array(1) { ["product_id"]=> int(11) } } }
The following code would simply solve your problem:
function DeleteProduct($pid) {
foreach ($_SESSION['products'] as $key => $product) {
if ($pid === $product['product_id']) {
unset($_SESSION['products'][$key]);
}
}
}
But to make your work alot easier in the future you could also build your array like this:
$_SESSION['products'] = array(
'product_id' => 'amount',
);
To add a product you would simply do:
$_SESSION['products'][$product_id] += $amount;
To count your products you could use:
count($_SESSION['products']);
Here is a simple example of what your functions could be like:
function addProduct($pid, $value = 1) {
$_SESSION['products'][$pid] += $value;
}
function removeProduct($pid) {
unset($_SESSION['products'][$pid]);
}
function countProducts() {
return count($_SESSION['products']);
}
Good luck!

add keys to php array

I'm trying to build an array for feeding my Graph. I use the code below:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
$i = 0;
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$i]['x'] = $value;
$_rows[$i]['y'] = $value;
$i++;
}
}
This results in the following response:
array(48) {
[0]=>
array(2) {
["x"]=>
string(7) "3283581"
["y"]=>
string(7) "3283581"
}
[1]=>
array(2) {
["x"]=>
string(10) "2013-10-16"
["y"]=>
string(10) "2013-10-16"
}
So it isn't okay yet.. it should say:
array(48) {
[0]=>
array(2) {
["x"]=>
string(7) "3283581"
["y"]=>
string(7) "2013-10-16"
}
[1]=>
array(2) {
["x"]=>
string(10) "1512116"
["y"]=>
string(10) "2013-10-17"
}
Can anyone tell me what I need to adjust in order to get the right output?
/////////////////////////////////
this is what's in $rows (a part of the output)
array(24) {
[0]=>
object(stdClass)#169 (2) {
["SUM(positive)"]=>
string(7) "3283581"
["DATE(stamp)"]=>
string(10) "2013-10-16"
}
[1]=>
object(stdClass)#160 (2) {
["SUM(positive)"]=>
string(7) "1512116"
["DATE(stamp)"]=>
string(10) "2013-10-17"
}
I think the first step here is to fix your output array from the Codeigniter model. Did you create:
$rows = $this->Website_model->getGraphDataPositives();
If so, you should be able to easily go into the function and change the output of the select statement.
Where you find "SUM(positive)" and "DATE(stamp)" in the function getGraphDataPositives(), change it to this (rough example, I don't know what the function looks like):
SUM(positive) AS x
DATE(stamp) AS y
Now you can just run it this way instead:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
foreach ($rows as $i => $row) {
foreach ($row as $column => $value) {
$_rows[$i][$column] = $value;
}
}
Also notice that I removed the $i = 0 and $i++ and replaced $key wit $i. Much easier that way.
Let me know if this helps.
EDIT: I accidentally kept the second $_rows[$i][$column] = $value; in there; that's not needed anymore. You only need one, and the way you have it set up its setting the same value to both entries.
EDIT 2: Just wanted to note that the above example may not be the best option, the best option would be to give more description aliases.
SUM(positive) AS positive
DATE(stamp) AS timestamp
Then set the values like this:
foreach ($rows as $i => $row) {
$_rows[$i]['x'] = $row->positive;
$_rows[$i]['y'] = $row->timestamp;
}
Either option will work, the first is just a little easier.
It would be easier if i knew the column names from SQL but here goes:
$rows = $this->Website_model->getGraphDataPositives();
$_rows = array();
foreach ($rows as $row) {
$_rows[] = array(
'x'=>$row['x-column-name-here'],
'y'=>$row['y-column-name-here']
);
}
foreach ($rows as $key => $row) {
// here $key is index, $row is the object
foreach ($row as $column => $value) {
// here $column will be "SUM(positive)" and the value will be 3283581
// for the first iteration. Since both are assigned $value
// $_rows[$i]['x'] and $_rows[$i]['y'] will be identical
$_rows[$i]['x'] = $value;
$_rows[$i]['y'] = $value;
$i++;
}
}
If you just use the object columns as you defined you should be ok:
foreach ($rows as $row) {
$_rows[$i]['x'] = $row->{'SUM(positive)'};
$_rows[$i]['y'] = $row->{'DATE(stamp)'};
}
You're also not using $key so might as well get rid of that as well.
Your example is kind of basic but I think this should solve its issues:
foreach ($rows as $key => $row) {
foreach ($row as $column => $value) {
$_rows[$key][$column%2==0?'x':'y'] = $value;
}
}
Provided you're using PDO::FETCH_NUM, ie your $rows are numerically indexed.

PHP array argument by value, gets modified when looping the array items by reference

I have been having issues with an array being modified when passed by value to a function.
I have inspected the code and inside the function the array is looped getting the elements by reference.
I was surprised to see that after the loop the array items are marked as referenced. I don't know what this means, but must be the origin of my problem.
Let me put an example to see the point.
<?php
error_reporting(E_ALL);
ini_set('display_errors' , 1);
$a = array( array(0) );
echo '--1--';var_dump($a);
dummy($a);
echo '--4--';var_dump($a);
function dummy($arg) {
foreach($arg as &$item) {
$item[0] = 3;
}
dummy2($arg);
echo '--3--';var_dump($arg);
}
function dummy2($arg) {
foreach($arg as &$item) {
$item[1]=9;
}
echo '--2--';var_dump($arg);
}
?>
After this code I would expect that in point 3, $arg would have only one element, but it has two, so it has been modified by dummy2 function.
The output is as follows:
--1--array(1) { [0]=> array(1) { [0]=> int(0) } }
--2--array(1) { [0]=> &array(2) { [0]=> int(3) [1]=> int(9) } }
--3--array(1) { [0]=> &array(2) { [0]=> int(3) [1]=> int(9) } }
--4--array(1) { [0]=> array(1) { [0]=> int(0) } }
Why are the arrays marked as &array after being looped by reference?
How can this be avoid?
You need to unset the loop variable that captures by reference:
<?php
error_reporting(E_ALL);
ini_set('display_errors' , 1);
$a = array( array(0) );
echo '--1--';var_dump($a);
dummy($a);
echo '--4--';var_dump($a);
function dummy($arg) {
foreach($arg as &$item) {
$item[0] = 3;
}
unset($item);
dummy2($arg);
echo '--3--';var_dump($arg);
}
function dummy2($arg) {
foreach($arg as &$item) {
$item[1]=9;
}
unset($item);
echo '--2--';var_dump($arg);
}
?>
See in the documentation for foreach, there is a big red warning that says:
Reference of a $value and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset().
Use key => value pairs and return the array in your functions
<?php
error_reporting(E_ALL);
ini_set('display_errors' , 1);
$a = array( array(0) );
echo '--1--';var_dump($a);
$a = dummy($a);
echo '--4--';var_dump($a);
function dummy($arg) {
foreach($arg as $key => $value) {
$arg[$key][0] = 3;
}
return dummy2($arg);
}
function dummy2($arg) {
foreach($arg as $key => $value) {
$arg[$key][1]=9;
}
return $arg;
}
?>
http://codepad.org/f30c6FUj

Categories