I want to add up the corresponding prices - php

I want to reassemble the following array for each management_code, class_type.
$varArrayA = array(
array(
"manegement_code" => "1",
"class_type" => array('A','B','C')
),
array(
"manegement_code" => "2",
"class_type" => array('A','B','C')
),
array(
"manegement_code" => "3",
"class_type" => array('A','B','C')
)
);
$varArrayB = array(
array(
"manegement_code" => "1",
"class_type" => "A",
"price" => "200"
),
array(
"manegement_code" => "1",
"class_type" => "B",
"price" => "300"
),
array(
"manegement_code" => "1",
"class_type" => "B",
"price" => "300"
),
array(
"manegement_code" => "2",
"class_type" => "B",
"price" => "300"
)
);
I want this result
$varArrayB = array(
array(
"manegement_code" => "1",
"class_type" => "A",
"price" => "200"
),
array(
"manegement_code" => "1",
"class_type" => "B",
"price" => "600"
),
array(
"manegement_code" => "2",
"class_type" => "B",
"price" => "300"
)
);
I made it as follows.
I'm confused about incorporating conditions in class_type.
I would appreciate it if you could be help me.
foreach ($varArrayA as $i => $varValueA) {
foreach ($varArrayB as $rowow ){
if($rowow['manegement_code']==$varValueA['manegement_code']){
$varArrayC[$i]['manegement_code'] = $rowow['manegement_code'];
$varArrayC[$i]['class_type'] = $rowow['class_type'];
$num = $num+$rowow['price'];
$varArrayC[$i]['price'] = $num;
}
}
}

if(($rowow['manegement_code']==$varValueA['manegement_code']) && ($rowow['class_type']==$varValueA['class_type'])){
$varArrayC[$i]['manegement_code'] = $rowow['manegement_code'];
$varArrayC[$i]['class_type'] = $rowow['class_type'];
$num = $num+$rowow['price'];
$varArrayC[$i]['price'] = $num;
}
Just ask if the class_type is the same as well.

Related

Construct an associative array from 2 other arrays, and linked by a common key

Problem:
I would like to combine 2 associative arrays to make one. To link these arrays, the ID key is present in both.
Input:
To retrieve my contacts with api call, I have to do 2 requests :
First to retrieve contacts with Id, and email adresse
Second to get some informations like name, city etc.
The first one return an array like this :
$contactArray = array(
array(
"CreatedAt" => "2019-04-12T11:53:26Z",
"DeliveredCount" => 0,
"Email" => "terry#example.org",
"ExclusionFromCampaignsUpdatedAt" => "2019-04-28T09:21:35Z",
"ID" => 1864410583,
"IsExcludedFromCampaigns" => false,
"IsOptInPending" => false,
"IsSpamComplaining" => false,
"LastActivityAt" => "2019-04-28T09:21:35Z",
"LastUpdateAt" => "2019-04-28T09:21:35Z",
"Name" => "",
"UnsubscribedAt" => "",
"UnsubscribedBy" => ""
),
array(
"CreatedAt" => "2019-04-12T12:39:30Z",
"DeliveredCount" => 0,
"Email" => "duane#example.org",
"ExclusionFromCampaignsUpdatedAt" => "",
"ID" => 1864410588,
"IsExcludedFromCampaigns" => false,
"IsOptInPending" => false,
"IsSpamComplaining" => false,
"LastActivityAt" => "2019-04-12T12:39:30Z",
"LastUpdateAt" => "2019-04-12T12:39:30Z",
"Name" => "",
"UnsubscribedAt" => "",
"UnsubscribedBy" => ""
)
);
The second call, return an array like
$contactDataArray =
array(
array(
"ContactID" => 1864410583,
"Data" => array(
array(
"Name" => "firstname",
"Value" => "Mark"
),
array(
"Name" => "city",
"Value" => "Miami"
),
array(
"Name" => "name",
"Value" => "Terry"
),
array(
"Name" => "phone",
"Value" => "555-5555"
)
),
"ID" => 1864410583
),
array(
"ContactID" => 1864410588,
"Data" => array(
array(
"Name" => "firstname",
"Value" => "Jane"
),
array(
"Name" => "city",
"Value" => "New York"
),
array(
"Name" => "name",
"Value" => "Duane"
),
array(
"Name" => "phone",
"Value" => "555-5555"
)
),
"ID" => 1864410588
)
);
In $contactArray, the ID key matches with ContactID key and ID key in $contactDataArray
Attempt:
I want an array formatted like this :
$output = array(
array(
"Email" => "terry#example.org",
"ID" => 1864410583,
"firstname" => "Mark",
"city" => "Miami",
"name" => "Terry",
"phone" => "555-5555"
),
array(
"Email" => "duane#example.org",
"ID" => 1864410588,
"firstname" => "Jane",
"city" => "New York",
"name" => "Duane",
"phone" => "555-5555"
)
);
I'm trying to achieve this with array_walk, but no succeed.
You can do this with foreach,
$result = [];
foreach ($contactDataArray as $key => $value) {
$ids = array_column($contactArray, "ID"); // fetching all values from contactArray
if (!empty(array_intersect([$value['ContactID'], $value['ID']], $ids))) { // checking if both satisfy the condition
$result[$key] = array_column($value['Data'], 'Value', 'Name'); // combining name and value
// searchng for key with matched ContactID
$result[$key]['Email'] = $contactArray[array_search($value["ContactID"], $ids)]['Email'];
$result[$key]['ID'] = $value["ContactID"];
}
}
Demo.
Can you please try with this?
$output = [];
for($i = 0; $i < count($contactDataArray); $i++) {
$arrIDandEmail = [
'Email' => isset($contactArray[$i]['Email']) ? $contactArray[$i]['Email'] : '',
'ID' => isset($contactDataArray[$i]['ID']) ? $contactDataArray[$i]['ID'] : ''
];
$arrData = array_column($contactDataArray[$i]["Data"], "Value", "Name");
$newArray = array_merge($arrIDandEmail, $arrData);
$output[] = $newArray;
}
For PHP >= 7.1 you can use array destructuring using list()
<?php
$output = [];
foreach ($contactDataArray as [
'ID' => $id,
'Data' => [
['Name' => $firstnameKey, 'Value' => $firstnameValue],
['Name' => $cityKey, 'Value' => $cityValue],
['Name' => $nameKey, 'Value' => $nameValue],
['Name' => $phoneKey, 'Value' => $phoneValue]
]
]) {
$output[] = [
"Email" => $contactArray[array_search($id, array_column($contactArray, 'ID'))]['Email'],
"ID" => $id,
$firstnameKey => $firstnameValue,
$cityKey => $cityValue,
$nameKey => $nameValue,
$phoneKey => $phoneValue
];
}
var_dump($output);
Demo
You can use array_walk,array_combine,array_column for the desired array as a result
$res = [];
array_walk($contactArray, function($v, $k) use ($contactDataArray,&$res)
{
$res[] = array_merge(['Email'=>$v['Email'],'ID'=>$v['ID']],
array_combine(
array_column($contactDataArray[$k]['Data'],'Name'),
array_column($contactDataArray[$k]['Data'],'Value')
)
);
});
echo '<pre>';
print_r($res);
DEMO

Best way to parse json_decoded php array

what would be the best way to parse stringified one dimensional array?
input array
$inputArray = array(
"id" => "foo",
"name" => "bar",
"money[0][amount]" => 30,
"money[0][countryCode]" => "US",
"money[1][amount]" => 25,
"money[1][countryCode]" => "CA",
)
desired output array
$outputArray = array(
"id" => "foo",
"name" => "bar",
"money" => array(
[0] => array(
"amount" => 30,
"countryCode" => "US"
),
[1] => array(
"amount" => 25,
"countryCode" => "CA"
),
),
)
You can convert your array in a query url and parse it ... like this
<?php
$inputArray = array(
"id" => "foo",
"name" => "bar",
"money[0][amount]" => 30,
"money[0][countryCode]" => "US",
"money[1][amount]" => 25,
"money[1][countryCode]" => "CA",
);
$url = http_build_query($inputArray);
parse_str($url, $outputArray);
print_r($outputArray);
Live example: https://3v4l.org/DAAUM

multi-dimensional array hierarchy

I like to know how can I get the hierarchy by the identifier.
This is an example :
$inputArray = array(
array(
"text" => "Dir1",
"parent_id" => "",
"id" => "1",
"filesize" => "109"
),array(
"text" => "dir2",
"parent_id" => "",
"id" => "2",
"filesize" => "88",
"children" => array(
"text" => "Dir3",
"parent_id" => "2",
"id" => "3",
"filesize" => "",
"children" => array(
"text" => "dir4",
"parent_id" => "3",
"id" => "4",
"filesize" => "",
"children" => array(
"text" => "dir5",
"parent_id" => "4",
"id" => "4",
"filesize" => ""
)
)
)
));
looking for this example :
dir3/dir4/dir5
function getText($array) {
$save[] = $array['text'];
if (isset($array['children'])) {
$save = array_merge($save, getText($array['children']));
}
return $save;
}
foreach($inputArray as $x) {
echo implode('/', getText($x)) . "\n";
}
result
Dir1
dir2/Dir3/dir4/dir5
demo

Array to repeat

$a = array(
array(
"name" => "jack",
"data" => "123",
"link_uid" => "1",
),
array(
"name" => "jack",
"data" => "134",
"link_uid" => "2",
),
array(
"name" => "tom",
"data" => "567",
"link_uid" => "3",
),
array(
"name" => "tom",
"data" => "098",
"link_uid" => "4",
)
);
to
$a = array(
array(
"name" => "jack",
"data" => "123",
"link_uid" => "1",
),
array(
"name" => " ",
"data" => "134",
"link_uid" => "2",
),
array(
"name" => "tom",
"data" => "567",
"link_uid" => "3",
),
array(
"name" => " ",
"data" => "098",
"link_uid" => "4",
)
);
Do you want just repeated name to blank
<?php
$temp = array();
foreach($a as $key=>$value){
if(in_array($value["name"],$temp)){
$a[$key]["name"] = "";
}else {
$temp[] = $value["name"];
}
}
print_r($a);
?>
Live demo : https://eval.in/855975

How to consolidate duplicate elements of this array in PHP?

I have an array like this:
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
It contains data from different orders, but as you can see an order can contain multiple purchased products, and each product can contain different 'components'. There's alot of duplicate data in this array, so I would like to turn it into this:
$array = array(
0 => array(
"order" => array(
"ordernumber" => "1", "name" => "John"
),
"products" => array(
0 => array(
"name" => "laptop",
"components" => array("memory", "cpu")
),
1 => array(
"name" => "desktop",
"components" => array("cpu")
)
)
),
1 => array(
"order" => array(
"ordernumber" => "2", "name" => "Pete"
),
"products" => array(
0 => array(
"name" => "monitor",
"components" => array()
)
)
)
);
What would be a good way to do this?
Please use below code to make the solution what you want
<?php
$array = array(
0 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "memory"),
1 => array("ordernumber" => "1", "name" => "John", "product" => "laptop", "component" => "cpu"),
2 => array("ordernumber" => "1", "name" => "John", "product" => "desktop", "component" => "cpu"),
3 => array("ordernumber" => "2", "name" => "Pete", "product" => "monitor", "component" => "")
);
$final_array = [];
foreach($array as $k=>$v){
$final_array[$v['ordernumber']]['order']['ordernumber'] = $v['ordernumber'];
$final_array[$v['ordernumber']]['order']['name'] = $v['name'];
$final_array[$v['ordernumber']]['products'][$v['product']]['name'] = $v['product'];
$final_array[$v['ordernumber']]['products'][$v['product']]['components'][] = $v['component'];
}
// You can skip this foreach if there will not metter of KEY of an array in your code!
$final_array = array_values($final_array);
foreach($final_array as $k=>$v){
$final_array[$k]['products'] = array_values($final_array[$k]['products']);
}
echo "<pre>";
print_r($final_array);
?>
its should work!!

Categories