Echo part of an array based on key => value match - php

I have an array structured like so:
<?php
$orderdata = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
);
?>
What I need to do is find the service_type_* part of the array, then echo all of the key value pairs until it reaches the next service_type_* where the loop then breaks.
Now this would be easy enough to do with a static data set but the array can change in size and each form can change depending on different variables, which is why the service_type_* key value entry is there.
Any ideas would be appreciated.
EDIT for clarification:
I basically need so that if I need, for example, the form data for web hosting, it would find the service_type_web key and return the following:
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
...And leaves out:
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
SECOND EDIT:
OK, I'm nearly there. I've come up with the following:
$delimiter = 0;
$array_counter = 0;
foreach($orderdata as $orderkey => $ordervalue) {
if($orderkey == "service_type_web") {
$new_array = array_slice($orderdata, $array_counter);
$array_counter ++;
$delimiter = 1;
} elseif(preg_match('/service_type_[a-z\_]+/', $orderkey)) {
if($delimiter == 1) {
echo $orderkey . " => " . $ordervalue . "<br />\n";
break;
}
} else {
$array_counter ++;
}
}
However the break in the if statement isn't working, even though when I get it to echo the key/value pair for the current array pointer, it echos
"service_type_ssl" => "on"
Anyone know why? Kinda stumped.

You can check "key" before you loop into it, by using array_key_exists
$orderdata = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
);
if (array_key_exists('service_type_web', $orderdata )) {
echo "array found";
}

A possible solution is. This answer may guide you in right direction but still you need to do some minor changes.
$input = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
);
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
$a = preg_grep_keys("/service_type_[a-z]*/", $input);
print_r($a);
expected output will be
Array ( [service_type_web] => on [service_type_ssl] => on )
taken from http://php.net/manual/en/function.preg-grep.php

Related

Assign values in array based on array keys

How to modify an array based on the value as key?
array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220825,
"totals" => 5614
)
);
I tried the following but it's not working:
foreach($cutoffs as $catoff) {
$ii = 0;
$sums[$ii][$catoff] = array_filter($array, function($val){
return $val['cutoff'] === $catoff ? $val['totals'] : $val;
});
$ii++;
}
My desired array:
array(
'20221025' => array(
12345,
12343,
24442
),
'20221110' => array(
3443,
744334
)
)
I'm stuck here for hours ... Please help
IF the "name" is irrelevant, I think also the previous answer should be fine.
If this code does "not work", then your explanation might be wrong, so you need to either explain better, or give us more examples - please mind that in your example the input and output are very different - the input you gave does not match your ouput.
My code is:
$a = array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 1234
)
);
print_r($a);
echo "\n================================\n\n";
$newArr = [];
foreach ($a as $k => $vArr) {
// maybe some validation would be useful here, check if they keys exist
$newArr[$vArr['cutoff']][] = $vArr['totals'];
}
print_r($newArr);
function changeArr($data){
$new = [];
foreach ($data as $v){
$new[$v['cutoff']][] = $v['totals'];
}
return $new;
}

How to change the way php returns the results of a sum with very small values

you will see maybe this problem sounds silly but it has tended me a bit stuck.
You see, I have a function which receives an array, with this array a sum must be made, specifically sum one of its columns (I enter as the third parameter of the function the column I want to sum).This work good. The problem is the way it generates the result. I show you my code:
function sumArray($array, $index, $col) {
$returnArray = []; // temporary container
// sanity checks
if (!is_array($array)) {
return 'error not an array';
}
$firstRow = reset($array);
if (!array_key_exists($index, $firstRow) || !array_key_exists($col, $firstRow)) {
return 'error keys provided not found';
}
foreach ($array as $value) {
if (!isset($returnArray[$value[$index]])) { // initialize
$returnArray[$value[$index]] = [$index => $value[$index], $col => 0];
}
// add value
$returnArray[$value[$index]][$col] += $value[$col]; //here is the sum
}
return $returnArray;
}
$products = array ( //this is the array
array("Id" => "000001",
"Name" => "Cheese",
"Quantity" => "0.00000012",
"Price" => "10"),
array("Id" => "000001",
"Name" => "Cheese",
"Quantity" => "0.00000123",
"Price" => "20"),
array("Id" => "000001",
"Name" => "Cheese",
"Quantity" => "0.00000020",
"Price" => "30"),
array("Id" => "000002",
"Name" => "Ham",
"Quantity" => "0.00000346",
"Price" => "200"),
array("Id" => "000002",
"Name" => "Ham",
"Quantity" => "0.000000998",
"Price" => "100"),
array("Id" => "000003",
"Name" => "Baicon",
"Quantity" => "0.000000492",
"Price" => "900")
);
$summedArray = sumArray($products, 'Name', 'Quantity');
print_r($summedArray);
the result of my sum is a new array. But look at the Quantity column:
Array (
[Cheese] => Array ( [Name] => Cheese [Quantity] => 1.55E-6 )
[Ham] => Array ( [Name] => Ham [Quantity] => 4.458E-6 )
[Baicon] => Array ( [Name] => Baicon [Quantity] => 4.92E-7 )
)
This form: 4.458E-6 I don't like. I would like something like this: 0.000004458
Do you know what I could do to get something like that? A suggestion would be of great help.
It isn't really related to the fact that it's a sum. That's just the default string representation of a small float in PHP. Try this, for example:
$number = 0.000004458;
echo $number; // displays 4.458E-6
The only reason the appearance changes in your output is that those values are strings in your input array, but when you add them together they are converted to floats.
If you want those values to display differently, you'll need to use some kind of formatting function that returns a string.
Assuming you aren't going to be using print_r to display the value in your final product, you can use number_format or printf to display it with however many decimal points you'd like.
foreach ($summedArray as $product => $info) {
echo number_format($info['Quantity'], 9) . PHP_EOL;
// or printf('%.9f', $info['Quantity']) . PHP_EOL;
}

Extracting from mulit-array and putting it into my own - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

Multidimensional array concatenate values of the same id(key)

How can I concatenate a key value if the id(key) value is the same as other id(key) value
PHP
$locations = Array(
[0] => Array(
"id" => 1,
"latitude" => "51.541561",
"longitude", => "84.215",
"content", => "The quick brown"
)
[1] => Array(
"id" => 1,
"latitude" => "51.541561",
"longitude", => "84.215",
"content", => "fox jumps over the lazy dog"
)
[2] => Array(
"id" => 3,
"latitude" => "12.541561",
"longitude", => "32.215",
"content", => "Another content"
)
)
And I want to make it like this:
$locations = Array(
[0] => Array(
"id" => 1,
"latitude" => "51.541561",
"longitude", => "84.215",
"content", => "The quick brown fox jumps over the lazy dog"
)
[2] => Array(
"id" => 3,
"latitude" => "12.541561",
"longitude", => "32.215",
"content", => "Another content"
)
)
Basically I want to concatenate the value in content(key) if the id(key) is the same with other id(key) value.
Any help would be greatly appreciated.
Try this -
$array = array();
foreach ($yourArray as $val) {
if (!array_key_exists($val['id'], $array)) {
$array[$val['id']] = $val;
} else {
$array[$val['id']]['content'] .= ' '.$val['content'];
}
}
hope this helps you :)
/**
* merge 2 arrays and return a new merged array. if same same key exists it will overwrite , unlike array_merge_recursive
* #param $a
* #param $b
* #return array|mixed
*/
public static function mergeArray($a,$b){
$args=func_get_args();
$res=array_shift($args);
while(!empty($args))
{
$next=array_shift($args);
foreach($next as $k => $v)
{
if(is_integer($k))
isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
$res[$k]=self::mergeArray($res[$k],$v);
else
$res[$k]=. $v;
}
}
return $res;
}

Sorting array by value

I have this array:
array(
"tour_0" => 1446,
"tour_1" => 1471,
"date-from-1471" => "2014-08-07",
"date-to-1471" => "2014-08-15",
"tour_2" => 30,
"date-from-30" => 2014-08-01,
"date-to-30" => 2014-08-05,
"tour_3" => 10
)
Now, i need it to be sorted to this:
array(
"0" => array("ID" => 1446),
"1" => array("ID" => 1471, "from" => "2014-08-07", "to" => "2014-08-15"),
"2" => array("ID" => 30, "from" => "2014-08-07", "to" => "2014-08-15"),
"3" => array("ID" => 10),
)
How can i accomplish this thing?
I've tried all sorts of things but i can't seem to figure this one out...
Thank's and sorry about the title but i just don't know how to describe it.
How about this?
$ret = [];
foreach($inputArray as $key => $value) {
if (preg_match('/^tour_([0-9]+)/', $key)) {
$ret[$value] = ["ID" => $value];
}
if (preg_match('/date-from-([0-9]+)/', $key, $matches)) {
$ret[$matches[1]]["from"] = $value;
}
if (preg_match('/date-to-([0-9]+)/', $key, $matches)) {
$ret[$matches[1]]["to"] = $value;
}
}
print_r($ret);
/*
Array
(
"1446" => Array ("ID" => 1446),
"1471" => Array ("ID" => 1471, "from" => "2014-08-07", "to" => "2014-08-15"),
"30" => Array ("ID" => 30, "from" => "2014-08-01", "to" => "2014-08-05"),
"10" => Array ("ID" => 10)
)*/
Close enough? (it is quite trival change the keys of the array, considering they are in order (0, 1, 2, 3, ...), if they are not, maybe you can save the order also (in another item of the subarray) and recompose again once this array is formed)

Categories