PHP foreach in a deeper array - php

How to foreach through a deeper array in PHP? I want to approach 'price' and list all prices below each other.
$addons = get_product_addons($product->get_id());
When I VAR_DUMP the $addons var, it outputs the below.
array(1) {
[0]=>
array(7) {
["name"]=>
string(8) "Afmeting"
["description"]=>
string(0) ""
["type"]=>
string(6) "select"
["position"]=>
int(0)
["options"]=>
array(10) {
[0]=>
array(5) {
["label"]=>
string(8) "70 x 200"
["price"]=>
string(0) "70.00"
["min"]=>
string(0)""
...
So I want to output this result:
70.00
60.00
Etcetera.. *All prices

I guess that piece of code is what you are looking for:
foreach($addons as $addon)
{
echo $addon["options"]["price"].PHP_EOL;
}
You do not need to use foreach to access nested elements of array. Just use it's key.
PHP_EOL is a constant containing newline for your OS. For web application use special formatting suitable for your page (<br> e.g.)

You can walk or foreach through the items:
<?php
$data =
[
[
'name' => 'orange',
'options' =>
[
'price' => '6.00'
]
],
[
'name' => 'banana',
'options' =>
[
'price' => '4.00'
]
]
];
array_walk($data, function($v) {
echo $v['options']['price'], "\n";
});
Output:
6.00
4.00
Or you could create an array of prices and iterate on that (here using short function syntax):
$prices = array_map(fn($v)=>$v['options']['price'], $data);
var_export($prices);
Output:
array (
0 => '6.00',
1 => '4.00',
)

Related

How To Insert Data Array to different table when he result is offset?

I have data as below:
Array
(
'action' => 'Buy',
'barcode' => '8993200661336',
'price' => 9000,
'intCode' => '30209423',
'quantity' => 1,
'promoDiscount' => Array
(
0 => Array
(
'promoId' => 'P00722000091',
'percentage' => 10,
'amount' => 900,
),
1 => Array
(
'promoId' => 'P00221000044',
'percentage' => 10,
'amount' => 900,
),
),
);
In Array promoDiscount value insert to different table, into 2 rows of data. if I insert intCode into the table, the value only goes to array index [0], while for array index[1] the result is offset.
how to insert intCode into index array[0] & index array[1] ?
If I understood correctly, you simply want to move the same intCode value inside the sub-arrays of promoDiscount.
You just need to add the additional parameter, looping either with for or foreach to make it dynamic. Like this:
<?php
foreach ($array['promoDiscount'] as $key => $val) {
$array['promoDiscount'][$key]['intCode'] = $array['intCode'];
}
?>
This will change your array to
["action"]=>
string(3) "Buy"
["barcode"]=>
string(13) "8993200661336"
["price"]=>
int(9000)
["intCode"]=>
string(8) "30209423"
["quantity"]=>
int(1)
["promoDiscount"]=>
array(2) {
[0]=>
array(4) {
["promoId"]=>
string(12) "P00722000091"
["percentage"]=>
int(10)
["amount"]=>
int(900)
["intCode"]=>
string(8) "30209423"
}
[1]=>
array(4) {
["promoId"]=>
string(12) "P00221000044"
["percentage"]=>
int(10)
["amount"]=>
int(900)
["intCode"]=>
string(8) "30209423"
}
}
}
Let's call your array $array
$array['promoDiscount'] [0] ['intCode'] = 'yourValue'
$array['promoDiscount'] [1] ['intCode'] = 'yourValue'
Or you can use for loop for
$array['promoDiscount']

Multidimensional Array as Variables to save in dB

I have a multidimensional array
output_querys = array(2) { [0]=> array(5) { ["ID"]=> string(1) "2" ["Code"]=> string(6) "AWS001" ["BCode"]=> string(4) "B001" ["Des"]=> string(4) "loan" ["subCat"]=> string(3) "SWA" } [1]=> array(5) { ["ID"]=> string(1) "4" ["Code"]=> string(6) "AWS002" ["BCode"]=> string(4) "B002" ["Des"]=> string(3) "tax" ["subCat"]=> string(3) "PJA" } }
I want to get this to a variable and then save into dB.I have tried all the methods that has mentioned in related problems nothing worked.
Errors I got
1.trying non-object
2.Illegal string offset
what I was trying to do is
foreach($output_querys as $output_query){
$Pv_ID = $output_query->ID;
$Pv_Code = $output_query->Code;
$Pv_Description = $output_query->Des;
$data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);
}
db->insert(abc, $data_final);
what is the problem here??.even i tried with json encode and still shows the "Illegal string offset"
$Pv_ID= json_decode($output_query['ID']);
$Pv_Code = json_encode($output_query['Code'],true);
$Pv_Description = json_encode($output_query['Des'],true);
I tried your given array and code
<?php
$output_querys = array(
0 => array(
"ID" => "2",
"Code" => "AWS001",
"BCode" => "B001",
"Des" => "loan",
"subCat" => "SWA"
),
1 => array(
"ID" => "4",
"Code" => "AWS002",
"BCode" => "B002",
"Des" => "tax",
"subCat" => "PJA"
)
);
foreach($output_querys as $output){
print_r($output['Code']); echo "\n";
}
?>
It is working fine on my end. Here's the working example
I think you need to do this as well, if you want to insert 1 by 1 then move the insert in foreach loop
foreach($output_querys as $output_query){
$Pv_ID = $output_query->ID;
$Pv_Code = $output_query->Code;
$Pv_Description = $output_query->Des;
$data_final = array(id => $Pv_ID, code => $Pv_Code, des => $Pv_Description);
db->insert(abc, $data_final);
}

Diference between $var = array($key => array()) VS $var[] = array($key => array())

i have a question about these 2 ways of declaring the array (I thought they would be the same):
$result[$zone->id]['activities'][$activity->id] = array(
'title' => $activity->title,
'image' => $activity->image
);
$result[$zone->id]['activities'] = array(
$activity->id => array(
'title' => $activity->title,
'image' => $activity->image
)
);
So my goal is to provide an array that is sorted by the Zone then by it's activities listed under the array of "activities".
The first array gives me the following result which is correct for my example:
array(3) {
[5]=>
array(2) {
["title"]=>
string(15) "Oftalmologistas"
["image"]=>
string(28) "logotipo_1575907014_4232.png"
}
[6]=>
array(2) {
["title"]=>
string(7) "Óticas"
["image"]=>
string(28) "logotipo_1575907021_1130.png"
}
[7]=>
array(2) {
["title"]=>
string(21) "Outras especialidades"
["image"]=>
string(28) "logotipo_1575907034_8988.png"
}
}
But the second array gives me the last activity found and replaces the two above it doesn't add them to array instead it replaces them.
array(1) {
[7]=>
array(2) {
["title"]=>
string(21) "Outras especialidades"
["image"]=>
string(28) "logotipo_1575907034_8988.png"
}
}
My goal here is to understand the diference syntax between them why the first adds them to array while the seconds replaces. Also any other way of declaring the array to the same first value. Thanks in advance!
this is just simple nested arrays with different keys and values for better understanding i change it to this code:
$result[100]['activities'][200] = array(
'title' => 4000,
'image' => 3000
);
$result[300]['product'] = array(
444444=> array(
'title' => 5000,
'image' => 6000
)
);
echo '<pre>';
var_dump($result);
first we have two array and inside each of them again there is another two arrays with different key and values if you look at this picture i uploaded i think you can understand completely.
nested array result
for first example
$result[$zone->id]['activities'][$activity->id] = array(
'title' => $activity->title,
'image' => $activity->image
);
You are assigning value to key "$activity->id"
Here as id gone be dynamic it will create new key everytime.
In second example
$result[$zone->id]['activities'] = array(
$activity->id => array(
'title' => $activity->title,
'image' => $activity->image
)
);
You are assiging value/array to activities.
So every time you try to assign value to activities key it will
replace it.

PHP array cannot use key to get value

I have this array:
Array ( ["id"] => 2015020052 ["gs"] => 5 ["ts"] => "THURSDAY 10/15"
["tsc"] => "final" ["bs"] => "FINAL" ["bsc"] => "final"
["atn"] => "Chicago" ["atv"] => "blackhawks" ["ats"] => "1"
["atc"] => "" ["htn"] => "Washington" ["htv"] => "capitals"
["hts"] => "4" ["htc"] => "winner" ["pl"] => true ["rl"] => true
["vl"] => true ["gcl"] => true ["gcll"] => true ["ustv"] => ""
["catv"] => "" )
I am trying to get particular values, like home team and away team and the scores, but I cannot get the values.
I am trying this:
echo "away team is ". $array['atv'];
But i just get
away team is
What am i missing????
var_dump gives me this:
Array vs array(21) { [""id""]=> string(10) "2015020051"
[""gs""]=> string(1) "5" [""ts""]=> string(16) ""THURSDAY 10/15"
[""tsc""]=> string(7) ""final"" [""bs""]=> string(7) ""FINAL""
[""bsc""]=> string(7) ""final"" [""atn""]=> string(8) ""Ottawa""
[""atv""]=> string(10) ""senators"" [""ats""]=> string(3) ""0""
[""atc""]=> string(2) """" [""htn""]=> string(12) ""Pittsburgh""
[""htv""]=> string(10) ""penguins"" [""hts""]=> string(3) ""2""
[""htc""]=> string(8) ""winner"" [""pl""]=> string(4) "true"
[""rl""]=> string(4) "true" [""vl""]=> string(4) "true"
[""gcl""]=> string(4) "true" [""gcll""]=> string(4) "true"
[""ustv""]=> string(2) """" [""catv""]=> string(2) """" }
I was also facing the same problem.
Problem:
The array was retrieved in Database [saved as a JSON encoded variable].
I was not getting the array element by key like $arr['key']
Solution:
Tried everything, no success.
Lastly, tried json_decode() and json_encode().
$arr = json_decode(json_encode($arr), TRUE);
Note that second parameter TRUE is very important. Otherwise, you will get object returned.
And it worked like charm.
You are not doing a correct associative array, this must be like this:
<?php
$array = [
'id' => 2015020052,
'gs' => 5,
'ts' => "THURSDAY 10/15",
'tsc' => "final",
'bs' => "FINAL",
'bsc' => "final",
'atn' => "Chicago",
...
];
Now you can get the value:
echo "away team is ". $array['atv'];
Here is the Demo

PHP suppress part of array if duplicate

I have an array of database objects and I'm using foreach() to present the names and projects. Good, now the customer doesn't want duplicate names for when one person has multiple projects. This has to do with variable scope and this is my failed attempt to pull this stunt off. Here's a partial var_dump of the array of objects.
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "analysis of foot"
}
]
What I want to end up with is:
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) ""
["projectName"]=>
string(16) "analysis of foot"
}
]
Here's what I was thinking that doesn't seem to work:
function suppress_name($name){
global $string;
return ($name == $string) ? '' : $string;
}
function overall() {
//$result = database call to get objects
foreach ($result as $item) {
$string = $item->lastName;
$rows = array('Name' => suppress_name($item->lastName), 'project' => $item->projectName);
}
}
Researching I see several references to array_unique() which I use for a flattened array, but I can't see that it would help me here. OK, I thought I could make a function, like the above, to handle duplicates and use the $global but think I'm not grasping how to use globals in this instance. I'm happy to be pointed to a better way, or better search terms. Does this make sense?
Here is a possible approach to your solution, where we store the last names in a one dimensional array then check against it through each iteration of the array. If the lastName is in the array then set the value to ''.
Note the use of the reference (&).
<?php
$arrays = array(
array('lastName' => 'w', 'projectName' => 'Bone density scanner analysis'),
array('lastName' => 'w', 'projectName' => 'analysis of foot')
);
$last_names = array();
foreach($arrays as &$array){
if( in_array($array['lastName'],$last_names) ){
$array['lastName'] = '';
}else{
$last_names[] = $array['lastName'];
}
}
echo '<pre>',print_r($arrays),'</pre>';
It would be easier to work with nested arrays
array [
0 => {
["lastName"]=> string(1) "w"
["projects"]=> array [
0 => {
["projectName"] => string(29) "Bone density scanner analysis"
}
1 => {
["projectName"]=> string(16) "analysis of foot"
}
1 => {
["lastName"] => string(1) "x"
["projects"] => array [
0 => {
["projectName"] => string(16) "analysis of head"
} ]
}
]

Categories