This is my array.
array (
0 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_labour_cost',
'text_value' => '1000',
),
1 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_metal_weight',
'text_value' => '10',
),
2 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_stone_carat',
'text_value' => '10',
),
3 =>
(object) array(
'per_unit_price' => NULL,
'code' => 'dynamic_stone2_carat',
'text_value' => '10',
),
4 =>
(object) array(
'per_unit_price' => '10.00',
'code' => 'dynamic_metal',
'text_value' => NULL,
),
5 =>
(object) array(
'per_unit_price' => '20.00',
'code' => 'dynamic_stone',
'text_value' => NULL,
),
6 =>
(object) array(
'per_unit_price' => '50.00',
'code' => 'dynamic_stone2',
'text_value' => NULL,
),
)
In short,
Let's take an example =
I want to multiply => array[1]['text_value'] * array[4]['per_unit_price']
Because
array[1]['code'] = dynamic_metal_weight is substring of array[4]['code'] = dynamic_metal
As all code are dynamic so I cannot hard code condition.
And I tried using for each [scan all the array] but It will take a lot of time by traditional loops.
Please guide me.
As suggested by #Chris Haas, this solution is based on the same logic. Based on what I see above in problem description below could help you. Also have provided suggestions to improvise..
<?php
echo "<pre>";
// array of data received from database
$code_values = [
[
'per_unit_price' => NULL,
'code' => 'dynamic_labour_cost',
'text_value' => '1000'
],
[
'per_unit_price' => NULL,
'code' => 'dynamic_metal_weight',
'text_value' => '10'
],
[
'per_unit_price' => NULL,
'code' => 'dynamic_stone_carat',
'text_value' => '10'
],
[
'per_unit_price' => NULL,
'code' => 'dynamic_stone2_carat',
'text_value' => '10'
],
[
'per_unit_price' => '10.00',
'code' => 'dynamic_metal',
'text_value' => NULL
],
[
'per_unit_price' => '20.00',
'code' => 'dynamic_stone',
'text_value' => NULL
],
[
'per_unit_price' => '50.00',
'code' => 'dynamic_stone2',
'text_value' => NULL
]
];
// filter $code_values to extract an array of elements where "per_unit_price" is set i.e. text_value is NULL
// Suggestion to improvise: If from database, you can fetch codes where only per_unit_price are set then this array_filter will not be required
$per_unit_prices = array_filter($code_values, function($array_element) {
return is_null($array_element['text_value']);
});
// create array of per unit prices where code will be key and per_unit_price will be value
$per_unit_prices = array_column($per_unit_prices, 'per_unit_price', 'code');
echo "<br>per_unit_prices<br>";
print_r($per_unit_prices);
// filter $code_values to extract an array of elements where "text_value is set i.e. per_unit_price is NULL
// Suggestion to improvise: If you can fetch codes where only text_values are set then this array_filter will not be required
$text_values = array_filter($code_values, function($array_element) {
return is_null($array_element['per_unit_price']);
});
// create array of text_values where code will be key and text_value will be value
$text_values = array_column($text_values, 'text_value', 'code');
echo "<br>text_values<br>";
print_r($text_values);
$output = []; // array to store multiplication of per_unit_price and text_value of matching elements
foreach($text_values as $code => $value) {
// create key of per_unit_price by removing last string part starting with _
$per_unit_prices_key = implode('_', array_slice(explode('_', $code), 0, -1));
// check if per_unit_prices_key exits in $per_unit_prices array we created. If so, create output value
if(isset($per_unit_prices[$per_unit_prices_key])) {
$output[$code] = (float) $value * (float)$per_unit_prices[$per_unit_prices_key];
}
}
echo "<br>output<br>";
print_r($output);
This is the output of the above code.
per_unit_prices
Array
(
[dynamic_metal] => 10.00
[dynamic_stone] => 20.00
[dynamic_stone2] => 50.00
)
text_values
Array
(
[dynamic_labour_cost] => 1000
[dynamic_metal_weight] => 10
[dynamic_stone_carat] => 10
[dynamic_stone2_carat] => 10
)
output
Array
(
[dynamic_metal_weight] => 100
[dynamic_stone_carat] => 200
[dynamic_stone2_carat] => 500
)
Related
I have this data:
[2022-12-07 11:56:19] local.INFO: array (
'name' => NULL,
'import_period' => NULL,
'google_ads_account' => NULL,
'period' => NULL,
'period_date_from' => NULL,
'period_date_to' => NULL,
'id_campaigns' =>
array (
0 =>
array (
'id_campaign' => NULL,
),
),
'id_adgroups' =>
array (
0 =>
array (
'id_adgroup' => NULL,
),
),
'campaign_name_contains' => NULL,
'adgroup_name_contains' => NULL,
'click' => 'less_than',
'click_value' => NULL,
'click_from' => NULL,
'click_to' => NULL,
'impressions' => 'less_than',
'impressions_value' => NULL,
'impressions_from' => NULL,
'impressions_to' => NULL,
'cost' => 'less_than',
'cost_value' => NULL,
'cost_from' => NULL,
'cost_to' => NULL,
'conversions' => 'less_than',
'conversions_value' => NULL,
'conversions_from' => NULL,
'conversions_to' => NULL,
'mapping_list' =>
array (
0 =>
array (
'value' => 'conversions',
'text' => NULL,
),
1 =>
array (
'value' => 'roas',
'text' => NULL,
),
2 =>
array (
'value' => 'all_conversions',
'text' => NULL,
),
3 =>
array (
'value' => 'all_conversions_from_interactions_rate',
'text' => NULL,
),
4 =>
array (
'value' => 'ctr',
'text' => NULL,
),
5 =>
array (
'value' => 'average_cpc',
'text' => NULL,
),
6 =>
array (
'value' => 'clicks',
'text' => NULL,
),
7 =>
array (
'value' => 'impressions',
'text' => NULL,
),
8 =>
array (
'value' => 'cost',
'text' => NULL,
),
9 =>
array (
'value' => 'conversions_value',
'text' => NULL,
),
10 =>
array (
'value' => 'conversions_from_interactions_rate',
'text' => NULL,
),
11 =>
array (
'value' => 'cost_per_conversion',
'text' => NULL,
),
12 =>
array (
'value' => 'search_click_share',
'text' => NULL,
),
13 =>
array (
'value' => 'search_impression_share',
'text' => NULL,
),
14 =>
array (
'value' => 'value_per_all_conversions',
'text' => NULL,
),
15 =>
array (
'value' => 'value_per_conversion',
'text' => NULL,
),
),
)
I am validating this data like this:
$validator = Validator::make($request->all(), [
'name' => 'required',
'import_period' => 'required',
'google_ads_account' => 'required',
'period' => 'required',
'period_date_from' => 'required_if:period,custom',
'period_date_to' => 'required_if:period,custom',
'id_campaigns.*.id_campaign'=> 'required',
'id_adgroups.*.id_adgroup' => 'required',
'campaign_name_contains' => 'required',
'adgroup_name_contains' => 'required',
'mapping_list.*.text' => 'required|min:1',
'click' => 'required',
'click_value' => 'required_if:click,greater_than,less_than',
'click_from' => 'required_if:click,between',
'click_to' => 'required_if:click,between',
'cost' => 'required',
'cost_value' => 'required_if:cost,greater_than,less_than',
'cost_from' => 'required_if:cost,between',
'cost_to' => 'required_if:cost,between',
'impressions' => 'required',
'impressions_value' => 'required_if:impressions,greater_than,less_than',
'impressions_from' => 'required_if:impressions,between',
'impressions_to' => 'required_if:impressions,between',
'conversions' => 'required',
'conversions_value' => 'required_if:conversions,greater_than,less_than',
'conversions_from' => 'required_if:conversions,between',
'conversions_to' => 'required_if:conversions,between',
]);
Here on this line 'mapping_list.*.text' => 'required|min:1' I am trying to validate this mapping_list array.
I want at least one field should be filled up but I have to fill up every element of this array.
Can you tell me is there anyting I am doing wrong?
If you want to validate that at least one field is filled, you must specify which field you want to validate. For example (in your code):
'mapping_list.*.text' => 'required|min:1',
you can change
'mapping_list.[0].text' => 'required|min:1',
or
'mapping_list.[1].text' => 'required|min:1',
That should be all you need to do. Hopefully that helps!
I have an array with the following format.
Example Json for reference:
https://jsoneditoronline.org/#left=cloud.42c7485653ea40549da90cf4338f8b23
I want to add "super_parent_id" in each of the childData arrays.
So if childData exists, i need to append super_parent_id to that child array. Similarly if a childData array exists within that array, i need to append super_parent_id to that child array.
I think recursion can solve this issue but I am not sure how to do it.
Thank you.
Yes, correct, recursion is one of the approaches for the problem. Here is a code snippet explaining how to implement the recursive modification of such data structure.
function appendSuperParentId(&$elem, $superParentId){
$elem["super_parent_id"] = $superParentId;
if (isset($elem["childData"])){
appendSuperParentId($elem["childData"], $superParentId);
}
}
$elems = [
[
"name" => "xyz",
"childData" => [
"name" => "foo",
"childData" => [
]
]
]
];
for ($i = 0; i < count($elems); $i++){
appendSuperParentId($elems[$i]["childData"], $superParentId);
}
not tested, but idea should work.
I've a cleaner solution using foreach:
<?php
$data = array (
'data' =>
array (
'valueId' => '21803826062',
'hasChildren' => true,
'parentId' => '21768700190',
'name' => 'Test Unit 002',
'childData' =>
array (
21810803918 =>
array (
'valueId' => '21810803918',
'hasChildren' => false,
'parentId' => '21803826062',
'name' => 'Test Unit 003',
'childData' => NULL,
'adUnitCode' => 'Test_unit_003',
'adUnitSizes' => NULL,
'adType' => 'TEXT_AND_IMAGE',
'smartSizeMode' => 'NONE',
),
21810890245 =>
array (
'valueId' => '21810890245',
'hasChildren' => false,
'parentId' => '21803826062',
'name' => 'Test Unit 002_1',
'childData' => NULL,
'adUnitCode' => 'test_unit_002_1',
'adUnitSizes' => NULL,
'adType' => 'TEXT_AND_IMAGE',
'smartSizeMode' => 'NONE',
),
),
'adUnitCode' => 'unit002',
'adUnitSizes' => NULL,
'adType' => 'TEXT_AND_IMAGE',
'smartSizeMode' => 'NONE',
),
);
$parentId = $data['data']['parentId'];
foreach($data['data']['childData'] as $key => $value){
$data['data']['childData'][$key]['super_parent_id'] = $parentId;
}
print_r($data);
PHP Sandbox link
array (
'_attributes' =>
array (
'name' => 'Rothco Product API - Variations',
),
'item_variations' =>
array (
0 =>
stdclass::__set_state(array(
'item_variation_id' => 2,
'item_index' => 3146,
'rothco_item_no' => '10002',
'upc' => '023063601212',
'inventory' => 99,
'created_date' => '2014-11-28 10:06:45.000',
'weight' => '.4000',
'image_filename' => '10002-A.jpg',
'catalog_page_no' => 183,
'msrp' => '20.9900',
'map' => '.0000',
'diameter' => '',
'price' => '8.100000',
'case_price' => NULL,
'case_quantity' => NULL,
'statuses' => '',
)),
),
)
This is my array $list.
I want to access 'item_variations' value from this array,
but if I try $list['item_variations'], or $list->['item_variations']
it is not working
If you want to reach just item_variations then
echo $list['item_variations'];
is sufficient. Things get more tricky if you would like to i.e. get value if created_date from your sample data as you got mix of arrays and objects so that require different access:
echo $list['item_variations'][0]->created_date;
which would output
2014-11-28 10:06:45.000
this is my code where i am fetching my mysql record.
$parentChildArr=array();
//mysql query for fetching parent and child record
$selectparentMenu=mysql_query("SELECT `id`,`item_name`,`menu_type`,`parent` FROM `epic_master_menu`");
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$parentChildArr[]=$fetchparentMenu['id'];
$parentChildArr[]=$fetchparentMenu['item_name'];
$parentChildArr[]=$fetchparentMenu['menu_type'];
$parentChildArr[]=$fetchparentMenu['parent'];
}
var_export($parentChildArr); // exporting or printing arrays
// when i export the array i get this output.
array ( 0 => '1', 1 => 'Dashboard', 2 => 'item', 3 => '0',
4 => '2', 5 => 'Admission', 6 => 'item', 7 => '0', 8 => '3',
9 => 'Examination', 10 => 'item', 11 => '0', 12 => '4',
13 => 'CET', 14 => 'item', 15 => '0');
but the problem is that i want to build the array like this.
$newarr=array ( 'dataSource' => array ( 0 => array ( 'id' => '1',
'text' => 'Dashboard', 'expanded' => 'true', 'spriteCssClass' => 'rootfolder',
'items' => array ( 0 => array ( 'id' => '89', 'text' => 'Users',
'expanded' => true, 'spriteCssClass' => 'folder',
'items' => array ( 0 => array ( 'id' => '94', 'text' => 'Users',
'spriteCssClass' => 'html', ), 1 => array ( 'id' => '94',
'text' => 'Users', 'spriteCssClass' => 'html', ), 2 => array (
'id' => '94', 'text' => 'Users', 'spriteCssClass' => 'image' ) ) ) ) ) ));
database table view is...
i am not getting the logic that how to build the array like $newarr. thank you
not tested, but you need to defined a structure and then you need to go recursive... so you can check where is the parent entry to my child ...
function structure($data){
return array(
'id' => $data['id'],
'item_name' => $data['item_name'],
'menu_type' => $data['menu_type'],
'parent' => $data['parent'],
'expanded' => false,
'childs' => array()
);
}
function recursiveImport(&$parent, $data){
foreach($parent AS $key => $value){
if($value['id'] == $data['parent']){
$parent[$key]['childs'][] = structure($data);
$parent[$key]['expanded'] = true;
return true;
}
else{
if(count($value['childs']) > 0){
foreach($value['childs'] AS $key2 => $child){
$result = recursiveImport($parent[$key]['childs'][$key2], $data);
if($result === true) return true;
}
}
}
}
return false;
}
$newarr = array();
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$result = recursiveImport($newarr , $fetchparentMenu);
if($result === false){
$newarr[] = structure($fetchparentMenu);
}
}
//output array
array ( 0 => array ( 'id' => '1', 'item_name' => 'Dashboard', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 1 => array ( 'id' => '2', 'item_name' => 'Admission', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 2 => array ( 'id' => '3', 'item_name' => 'Examination', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 3 => array ( 'id' => '4', 'item_name' => 'CET', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), )
Use following code
$m=0;
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$parentChildArr[$m][]=$fetchparentMenu['id'];
$parentChildArr[$m][]=$fetchparentMenu['item_name'];
$parentChildArr[$m][]=$fetchparentMenu['menu_type'];
$parentChildArr[$m][]=$fetchparentMenu['parent'];
$m++;
}
The following output is a result of calling var_export($charge);
How can I access the output of 'paid'=>true from $charge? Any ideas would be appreciated.
I have tried $charge->_values->paid, $charge->paid, etc.. I haven't had any luck.
I have also tried $charge['_values']['paid'];
Stripe_Charge::__set_state(array(
'_apiKey' => 'sk_test_BPZyFpcAM',
'_values' =>
array (
'id' => 'ch_102kMF29T6',
'object' => 'charge',
'created' => 1381688,
'livemode' => false,
'paid' => true,
'amount' => 104000,
'currency' => 'usd',
'refunded' => false,
'card' =>
Stripe_Card::__set_state(array(
'_apiKey' => 'sk_test_BPZyFpc',
'_values' =>
array (
'id' => 'card_102kMF29T6',
'object' => 'card',
'last4' => '4242',
'type' => 'Visa',
'exp_month' => 2,
'exp_year' => 2015,
'fingerprint' => '7sRY4jiFM',
'customer' => NULL,
'country' => 'US',
'name' => NULL,
'address_line1' => NULL,
'address_line2' => NULL,
'address_city' => NULL,
'address_state' => NULL,
'address_zip' => NULL,
'address_country' => NULL,
'cvc_check' => 'pass',
'address_line1_check' => NULL,
'address_zip_check' => NULL,
),
'_unsavedValues' =>
Stripe_Util_Set::__set_state(array(
'_elts' =>
array (
),
)),
'_transientValues' =>
Stripe_Util_Set::__set_state(array(
'_elts' =>
array (
),
)),
'_retrieveOptions' =>
array (
),
)),
'captured' => true,
'refunds' =>
array (
),
'balance_transaction' => 'txn_102kMF29T6Z',
'failure_message' => NULL,
'failure_code' => NULL,
'amount_refunded' => 0,
'customer' => NULL,
'invoice' => NULL,
'description' => 'admin#fra.org',
'dispute' => NULL,
'metadata' =>
array (
),
),
'_unsavedValues' =>
Stripe_Util_Set::__set_state(array(
'_elts' =>
array (
),
)),
'_transientValues' =>
Stripe_Util_Set::__set_state(array(
'_elts' =>
array (
),
)),
'_retrieveOptions' =>
array (
),
))
You can use the __toArray($recursive = false) function to get the data in array form.
Example:
$chargeArray = $charge->__toArray(true);
echo $chargeArray['paid'];
I was also able to access the object's data using an array structure before even converting to an array. For me, $charge['paid'] gets me the value.
you can use __toArray() method:
$array = $collection->__toArray(true);
This will work for this case
whatever returns please parse it with json_decode and you will get a assoc array in php
i.e suppose return array is $ret
$ret = json_decode($ret);
$ret->paid;
$ret->captured;
$ret->card->id;
and so on..
Hope it will help you.
echo gettype($charge->paid); //boolean
var_dump($charge->paid); //bool(true)
if($charge->paid==true)echo "==true"; //==true
if($charge->paid===true)echo "===true"; //===true
if($charge->paid==1)echo "==1"; //==1
if($charge->paid===1)echo "===1"; //nada, it's a boolean, not numeric
So using if($charge->paid===true), you should be guaranteed that you are testing what you want to know.
Here in the output via print_r, you can see that paid is displayed as 1.
[_values:protected] => Array ( [id] => ch_10as29724hknftGBm9TxC [object] => charge [created] => 1384696845 [livemode] => [paid] => 1 [amount] => 1400
Thus, depending on where and how paid is being evaluated, it may appear as a number, string, or a boolean. You could run a series of tests for the three possibilities, or just use if($charge->paid){...}
When paid is false, it would probably be returned as empty (""), 0, or a boolean false. A possible thing to look out for is the boolean false being transposed to a string, in which case it would be interpreted as true.
$val = "false";
if($val){
echo "true"; //true
}
So, in your test, just add intval($val) to normalize the values and be on the safe side.
if(intval($charge->paid)){...}
Cheers