PHP - Replace array keys with a list of keys predefined - php

I have a multidimensional array that I get after scrapping a web.
Array
(
[Dollar N. America] => Array
(
[Name] => Dollar N. America
[Buy] => 3.311
[Sell] => 3.314
)
[Yen Japan] => Array
(
[Name] => Yen Japan
[Buy] => 0.028
[Sell] => 0.033
)
[Euro Europe] => Array
(
[Name] => Euro Europe
[Buy] => 3.752
[Sell] => 3.948
)
)
The issue is that I need to change the names of the array keys to a shorter name:
[DollarUS] - [YenJP] - [EuroEU]
In order to make it look like this:
Array
(
[DollarUS] => Array
(
[Name] => Dollar N. America
[Buy] => 3.311
[Sell] => 3.314
)
[YenJP] => Array
(
[Name] => Yen Japan
[Buy] => 0.028
[Sell] => 0.033
)
[EuroEU] => Array
(
[Name] => Euro Europe
[Buy] => 3.752
[Sell] => 3.948
)
)
I was trying several ways but I did not find the result:
foreach ($currency as $k => $v){
$currency[$k]['DolarUS'] = $currency[$k]['Dollar N. America'];
unset($monedas[$k]['Dollar N. America']);
}

$array = [
"Dollar N. America" => [
"Name" => "Dollar N. America"
"Buy" => 3.311
"Sell" => 3.314
],
"Yen Japan" => [
"Name" => "Yen Japan"
"Buy" => 0.028
"Sell" => 0.033
],
"Euro Europe" => [
"Name" => "Euro Europe"
"Buy" => 3.752
"Sell" => 3.948
]
];
$replace_with_me = ["Dollar N. America"=>"DollarUS" , "Yen Japan"=>"YenJP" , "Euro Europe"=>"EuroEU"];
foreach($array as $key=>$value){
$array[$replace_with_me[$key]] = $array[$key];
unset($array[$key])
}
var_dump($array[$key]);

You could try array_combine():
http://php.net/manual/en/function.array-combine.php
$keys = ['DollarUS','YenJP','EuroEU'];
$values = [
'Dollar N. America' => [
'Name' => 'Dollar N. America'
'Buy' => 3.311
'Sell' => 3.314
],
'Yen Japan' => [
'Name' => 'Yen Japan'
'Buy' => 0.028
'Sell' => 0.033
],
'Euro Europe' => [
'Name' => 'Euro Europe'
'Buy' => 3.752
'Sell' => 3.948
]
];
$fixedKeys = array_combine($keys,$values);

Related

Group values in multi-dimensional array based on a key

I have the following multi-dimensional array:
Array
(
[0] => Array
(
[sname] => florida
[cname] => orlando
)
[1] => Array
(
[sname] => texas
[cname] => dallas
)
[2] => Array
(
[sname] => florida
[cname] => tampa
)
[3] => Array
(
[sname] => ohio
[cname] => columbus
)
)
How would I go about trying to get all 'cname' values associated with each 'sname' value?
florida: orlando, tampa
texas: dallas
ohio: columbus
There are probably several ways to do this. The one that comes to mind is something like this:
<?php
$payload = [];
$origin = [
[
'sname' => 'florida',
'cname' => 'orlando'
],
[
'sname' => 'texas',
'cname' => 'dallas'
],
[
'sname' => 'florida',
'cname' => 'tampa'
],
[
'sname' => 'ohio',
'cname' => 'columbus'
]
];
foreach ($origin as $value) {
if (! isset($payload[$value['sname']])) {
$payload[$value['sname']] = '';
}
$payload[$value['sname']] .= (strlen($payload[$value['sname']]) >0?',':'') . $value['cname'];
}
print_r($payload);
Cheers! :)
=C=
With a slight tweak of Mike's solution (https://stackoverflow.com/a/2189916/4954574), the following will produce what I was hoping for:
$input_arr = array(
array("sname" => "florida", "cname" => "orlando"),
array("sname" => "texas", "cname" => "dallas"),
array("sname" => "florida", "cname" => "tampa"),
array("sname" => "ohio", "cname" => "columbus")
);
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['sname']][$key] = $entry['cname'];
}
print_r($level_arr);
Output:
Array
(
[florida] => Array
(
[0] => orlando
[2] => tampa
)
[texas] => Array
(
[1] => dallas
)
[ohio] => Array
(
[3] => columbus
)
)

PHP arrays combine values of the right key

I have a question about arrays in PHP:
I have many zip files having many data inside and using preg_grep I could get the results below:
(These data are returned from multiple text files in the zip file)
=> Array
(
[ZipName] => data.zip
[Age] => 45
)
=> Array
(
[ZipName] => data.zip
[Name] => John
)
=> Array
(
[ZipName] => data2.zip
)
=> Array
(
[ZipName] => data1.zip
[Age] => 25
)
=> Array
(
[ZipName] => data2.zip
[Age] => 27
)
=> Array
(
[ZipName] => data1.zip
[Name] => Abram
)
=> Array
(
[ZipName] => data1.zip
)
=> Array
(
[ZipName] => data2.zip
[City] => London
)
=> Array
(
[ZipName] => data2.zip
[Name] => Inna
)
=> Array
(
[ZipName] => data1.zip
[City] => London
)
So how I can combine/merge all of these arrays using the ZipName Value !
Like in SQL it easy :
SELECT * FROM * WHERE ZipName= 'x';
0 => Array
(
[ZipName] => data.zip
[Age] => 45
[Name] => John
[City] => Leicester
)
1 => Array
(
[ZipName] => data1.zip
[Age] => 25
[Name] => Abram
[City] => London
)
2 => Array
(
[ZipName] => data2.zip
[Age] => 27
[Name] => Inna
[City] => London
)
An alternative to using array_merge, array_combine etc.. ...is just two simple foreach loops and setting the value into a new array ($new_arr).
$new_arr = [];
foreach($arr as $inner_arr) {
foreach($inner_arr as $key=>$value) {
$new_arr[$key] = $value;
}
}
UPDATE
I was not clear what OP wanted but I hope it's clearer now:
Try this:
(Basically adding values to array[name of ZipName][{current key for the inner array}]
$arr = [
[
'ZipName' => 'data.zip',
'Age' => '45'
],
[
'ZipName' => 'data.zip',
'Name' => 'John'
],
[
'ZipName' => 'data2.zip',
'Age' => '27'
],
[
'ZipName' => 'data1.zip',
'Name' => 'Abram'
],
[
'ZipName' => 'data1.zip'
],
[
'ZipName' => 'data2.zip',
'City' => 'London'
],
[
'ZipName' => 'data2.zip',
'Name' => 'Inna'
],
[
'ZipName' => 'data1.zip',
'City' => 'London'
]
];
$new_arr = [];
foreach($arr as $key => $inner_arr) {
foreach($inner_arr as $ik => $item) {
$new_arr[$inner_arr['ZipName']][$ik] = $item;
}
}
Output:
Array
(
[data.zip] => Array
(
[ZipName] => data.zip
[Age] => 45
[Name] => John
)
[data2.zip] => Array
(
[ZipName] => data2.zip
[Age] => 27
[City] => London
[Name] => Inna
)
[data1.zip] => Array
(
[ZipName] => data1.zip
[Name] => Abram
[City] => London
)
)
When doing:
$new_arr = array_values($new_arr);
the key simply gets do be a numeric index (if it matters)
Array
(
[0] => Array
(
[ZipName] => data.zip
[Age] => 45
[Name] => John
)
[1] => Array
(
[ZipName] => data2.zip
[Age] => 27
[City] => London
[Name] => Inna
)
[2] => Array
(
[ZipName] => data1.zip
[Name] => Abram
[City] => London
)
)
What you need is to group by the unique values at the index ['ZipName'] and then merge those groups individually. This can be done with array_reduce.
Example:
<?php
declare(strict_types=1);
$input = [
[
'ZipName' => 'data_1.zip',
'Age' => 45,
], [
'ZipName' => 'data_1.zip',
'Name' => 'John',
], [
'ZipName' => 'data_1.zip',
], [
'ZipName' => 'data_1.zip',
'City' => 'Leicester',
],
[
'ZipName' => 'data_2.zip',
'Age' => 45,
], [
'ZipName' => 'data_2.zip',
'Name' => 'John',
], [
'ZipName' => 'data_2.zip',
], [
'ZipName' => 'data_2.zip',
'City' => 'Leicester',
],
];
$output = array_values(array_reduce($input, static function (array $acc, array $item): array {
$acc[$item['ZipName']] = array_merge($acc[$item['ZipName']] ?? [], $item);
return $acc;
}, []));
print_r($output);
I think you are going to combine different arrays, So please use array merge.
$array0 = Array
(
"ZipName" => data.zip,
"Age" => 45
);
$array1 = Array
(
"ZipName" => data.zip,
"Name" => John
);
$array2 = Array
(
"ZipName" => data.zip
);
$array3 = Array
(
"ZipName" => data.zip,
"City" => Leicester
);
print_r(array_merge($array0, $array1, $array2, $array3));
Out Put:
Array ( [ZipName] => datazip
[Age] => 45
[Name] => John
[City] => Leicester )

How to get certain values from multidimensional arrays?

Here's the data I am working with right now:
$city = [
[
"name" => "Dhaka",
"areas" => ["d1", "d2", "d3"]
],
[
"name" => "Chittagong",
"areas" => ["c1", "c2", "c3"]
],
[
"name" => "Sylhet",
"areas" => ["s1", "s2", "s3"]
],
[
"name" => "Barisal",
"areas" => ["b1", "b2", "b3"]
],
[
"name" => "Khulna",
"areas" => ["k1", "k2", "k3"]
],
[
"name" => "Rajshahi",
"areas" => ["r1", "r2", "r3"]
],
];
I would like to get a list of data associated with only "name" key.
I would also like to show the data associated with "area" key once the user go for the corresponding "name".
It would be helpful if there were any suggestion on how to better store this data for frequent usage in code.
As long as the names are unique you can do this simple trick:
Example 1
$city = [
[
"name" => "Dhaka",
"areas" => ["d1", "d2", "d3"]
],
[
"name" => "Chittagong",
"areas" => ["c1", "c2", "c3"]
],
[
"name" => "Sylhet",
"areas" => ["s1", "s2", "s3"]
],
[
"name" => "Barisal",
"areas" => ["b1", "b2", "b3"]
],
[
"name" => "Khulna",
"areas" => ["k1", "k2", "k3"]
],
[
"name" => "Rajshahi",
"areas" => ["r1", "r2", "r3"]
],
];
$names = array_column($city, null, 'name');
print_r($names);
Output
Array
(
[Dhaka] => Array
(
[name] => Dhaka
[areas] => Array
(
[0] => d1
[1] => d2
[2] => d3
)
)
[Chittagong] => Array
(
[name] => Chittagong
[areas] => Array
(
[0] => c1
[1] => c2
[2] => c3
)
)
[Sylhet] => Array
(
[name] => Sylhet
[areas] => Array
(
[0] => s1
[1] => s2
[2] => s3
)
)
[Barisal] => Array
(
[name] => Barisal
[areas] => Array
(
[0] => b1
[1] => b2
[2] => b3
)
)
[Khulna] => Array
(
[name] => Khulna
[areas] => Array
(
[0] => k1
[1] => k2
[2] => k3
)
)
[Rajshahi] => Array
(
[name] => Rajshahi
[areas] => Array
(
[0] => r1
[1] => r2
[2] => r3
)
)
)
Now you can lookup by name
print_r($city['Chittagong']['areas']); //["c1", "c2", "c3"]
If the names are not guaranteed to be unique, you'll have to build them using foreach, like this:
Example 2
$city = [
[
"name" => "Dhaka",
"areas" => ["d1", "d2", "d3"]
],
[
"name" => "Chittagong",
"areas" => ["c1", "c2", "c3"]
],
[ /*--- ADDED to show duplication ---- */
"name" => "Chittagong",
"areas" => ["x1", "x2", "x3"]
],
[
"name" => "Sylhet",
"areas" => ["s1", "s2", "s3"]
],
[
"name" => "Barisal",
"areas" => ["b1", "b2", "b3"]
],
[
"name" => "Khulna",
"areas" => ["k1", "k2", "k3"]
],
[
"name" => "Rajshahi",
"areas" => ["r1", "r2", "r3"]
],
];
$output = [];
foreach($city as $k=>$v){
$k = $v['name'];
if(!isset($output[$k])) $output[$k] = []; //initialize
$output[$k][] = $v;
}
print_r($output);
Which will give you something like this:
Array
(
[Dhaka] => Array
(
[0] => Array
(
[name] => Dhaka
[areas] => Array
(
[0] => d1
[1] => d2
[2] => d3
)
)
)
[Chittagong] => Array
(
[0] => Array
(
[name] => Chittagong
[areas] => Array
(
[0] => c1
[1] => c2
[2] => c3
)
)
[1] => Array
(
[name] => Chittagong
[areas] => Array
(
[0] => x1
[1] => x2
[2] => x3
)
)
)
[Sylhet] => Array( ... )
As you can see this adds an extra level in to contain the multiple occurrences. Of course you could just combine the area when duplicate (in the foreach). But that is up to you.
Here is a quick example of that (same data as above):
Example 3
$output = [];
foreach($city as $k=>$v){
$k = $v['name'];
if(!isset($output[$k])) $output[$k] = []; //initialize
$output[$k] = array_merge($output[$k], $v['areas']); //merge the areas
}
print_r($output);
Output
Array
(
[Dhaka] => Array
(
[0] => d1
[1] => d2
[2] => d3
)
[Chittagong] => Array
(
[0] => c1
[1] => c2
[2] => c3
[3] => x1
[4] => x2
[5] => x3
)
....
)
If it was me, I would go with the last one, just because of the simplicity it will have working with it later.
PS. if your pulling data out of a Database with PDO, you can use $stmt->fetchAll(PDO::FETCH_GROUP) which will give you something like the second example automatically. The only caveat here is that the name column is the first one selected in the Query, which is the column it will group on.
Cheers.
If you're just trying to loop through the list of cities and get the names you can just use a foreach loop. If you need something beyond this try to define your question a little more.
foreach ($city as $c) {
echo $c["name"];
}

associative array check any column is empty or not

I have associative array like -
[0] => Array
(
[date] => 2018-06-22
[id] => 2282991
[type] => VIDEO
[domain] =>
[code] => Austin
[address] => Phone
)
[1] => Array
(
[date] => 2018-06-22
[id] => 2282991
[type] => VIDEO
[domain] =>
[code] =>
[address] => Phone
)
[3] => Array
(
[date] => 2018-06-22
[id] => 2282991
[type] => VIDEO
[domain] =>
[code] => Austin
[address] => Phone
)
I need to check is there any column having all the values are blank.
That means it should return only domain from above array because it is blank everywhere.
Is there any way to do this with minimum use of forloop? I need to check this for all these columns.
This will work if your subarray having same number of keys.Like "Date, id, Type etc".
$array = [
[ "date" => "2018-06-22", "id" => 2282991, "type" => "VIDEO", "domain" =>'', "code" => "Austin", "address" => "Phone"],
[ "date" => "2018-06-22", "id" => 2282991, "type" => "VIDEO", "domain" =>'', "code" => "", "address" => "Phone"],
[ "date" => "2018-06-22", "id" => 2282991, "type" => "VIDEO", "domain" =>'', "code" => "Austin", "address" => "Phone"]
];
$empty = [];
foreach($array[0] as $key=>$val){
$error = array_column($array, $key);
if(empty (array_filter($error)) ) {
$empty[] = $key;
}
}
print_r($empty);
Output:
Array
(
[0] => domain
)

Convert multidimensional array into single array with key and values?

This is my array,
array
(
[0] => Array
(
[Invoice_id] => 1
[Customer_Name] => Abcd Ltd
[Order_Created] => 2018-02-07
[Order_Delivery_Date] => 2018-02-17
[State_Code] => 35
[CGST] => 212.5
[SGST] => 212.5
[IGST] => 0
[Total_Amount] => 8925
)
[1] => Array
(
[Invoice_id] => 2
[Customer_Name] => Johnson and Sons
[Order_Created] => 2018-02-07
[Order_Delivery_Date] => 2018-02-17
[State_Code] => 35
[CGST] => 2975
[SGST] => 2975
[IGST] => 0
[Total_Amount] => 124950
)
)
How to convert this array like below,
array
(
array("invoice_id" => "1", "customer_name" => "Abcd Ltd", "order_created" => 2018-02-07, "delivery_date" => 2018-02-17, "state_code" => 35, "cgst" =>212.5, "sgst" =>212.5, "igst" =>0, "total_amount" =>8925),
array("invoice_id" => "2", "customer_name" => "Johnson and Sons", "order_created" => 2018-02-07, "delivery_date" => 2018-02-17, "state_code" => 35, "cgst" =>2975, "sgst" =>2975, "igst" =>512.5, "total_amount" =>124950)
);
You already have it in the format you want, they are just in different ways of displaying arrays, except that your arrays are indexed by keys, if you really want to unindex it use this $newArray = array_values($array)
You could try this to change keys of your array :
foreach ($array as $k => $item) {
foreach ($item as $key => $value) {
unset($array[$k][$key]) ; // remove old key
$array[$k][strtolower($key)] = $value ; // add new one
}
}
Then "Invoice_id" keys will be "invoice_id", and so on.

Categories