Combine array to one array - php

I have an array:
$settings = array(
'name' => array(
0 => 'Large Pouch',
1 => 'XL Pouch'
),
'size' => array(
0 => '9x14',
1 => '12x18'
),
'weight' => array(
0 => '10',
1 => '20'
),
'metro_manila_price' => array(
0 => '59',
1 => '79'
),
'luzvimin_price' => array(
0 => '89',
1 => '139'
)
);
I wanted to put the values from that array to one array. $shipping_options with format of
for example:
$shipping_options = array(
'0' => 'Large Pouch 9x14 - $59',
'1' => 'XL Pouch 12x18 - $79'
);
How to program this?

You could write a loop:
$shipping_options = array();
foreach ($settings['name'] as $key => $value) {
$value = sprintf('%s(%s) - $%s',
$value,
$settings['size'][$key],
$settings['metro_manila_price'][$key]);
$shipping_options[$key] = $value;
}

try this one
echo "<pre>";
$size = count($settings['name']);
$shipping_options = array();
for($i=0; $i<$size; $i++)
{
$shipping_options[$i] = $settings['name'][$i]."(".$settings['size'][$i].") - $".$settings['metro_manila_price'][$i];
}
print_r($shipping_options);

You can try this
foreach ($settings['name'] as $key => $value) {
$shipping_options[$key] = $settings['name'][$key] . " " . $settings['size'][$key] . " - $" . $settings['metro_manila_price'][$key];
}

Related

JSON php extract data (where a statement is true)

I'm trying to catch specific data from a weather forecast API request (JSON output). The request gives me data for the next 3 days but I only need the next day. Here a snippet of the output:
array (
'cod' => '200',
'message' => 0.00259999999999999988065102485279567190445959568023681640625,
'cnt' => 40,
'list' =>
array (
0 =>
array (
'dt' => 1526461200,
'main' =>
array (
'temp' => 292.93000000000000682121026329696178436279296875,
'temp_min' => 292.05000000000001136868377216160297393798828125,
'temp_max' => 292.93000000000000682121026329696178436279296875,
'pressure' => 1019.259999999999990905052982270717620849609375,
'sea_level' => 1029.170000000000072759576141834259033203125,
'grnd_level' => 1019.259999999999990905052982270717620849609375,
'humidity' => 71,
'temp_kf' => 0.88000000000000000444089209850062616169452667236328125,
),
'weather' =>
array (
0 =>
array (
'id' => 802,
'main' => 'Clouds',
'description' => 'scattered clouds',
'icon' => '03d',
),
),
'clouds' =>
array (
'all' => 36,
),
'wind' =>
array (
'speed' => 4.20000000000000017763568394002504646778106689453125,
'deg' => 37.00240000000000151203494169749319553375244140625,
),
'sys' =>
array (
'pod' => 'd',
),
'dt_txt' => '2018-05-16 09:00:00',
),
1 =>
array (
'dt' => 1526472000,
'main' =>
array (
'temp' => 293.6100000000000136424205265939235687255859375,
'temp_min' => 292.95800000000002683009370230138301849365234375,
'temp_max' => 293.6100000000000136424205265939235687255859375,
'pressure' => 1019.799999999999954525264911353588104248046875,
'sea_level' => 1029.65000000000009094947017729282379150390625,
'grnd_level' => 1019.799999999999954525264911353588104248046875,
'humidity' => 66,
'temp_kf' => 0.66000000000000003108624468950438313186168670654296875,
),
'weather' =>
array (
0 =>
array (
'id' => 803,
'main' => 'Clouds',
'description' => 'broken clouds',
'icon' => '04d',
),
),
'clouds' =>
array (
'all' => 56,
),
'wind' =>
array (
'speed' => 5.79999999999999982236431605997495353221893310546875,
'deg' => 38.0009000000000014551915228366851806640625,
),
'sys' =>
array (
'pod' => 'd',
),
'dt_txt' => '2018-05-16 12:00:00',
)
I'm trying to get the 'all' values where 'dt_txt' starts from 0am the next day to 0pam the day after.
For now I'm using the following php code without checking for dt_txt:
<?php
$url = "http://api.openweathermap.org/data/2.5/forecast?q=D%C3%BClmen,de&mode=json";
$response = file_get_contents($url);
$obj = json_decode($response);
$t = 0;
$regen = 0;
$regendiv = 0;
for($i=0; $i < 10; $i++) {
$fg = $obj->list[$i]->clouds->all;
$regen += $fg;
}
echo $regen;
?>
My code requires me to run the request at a specific time (like close to midnight) in order to catch the 'all' values for the next day. Is there any way to check for 'dt_text' = the next day?
My Idea would be something like this:
for($i=0; $i < 10; $i++) {
$fg = $obj->list[$i]->clouds->all;
if (strpos($obj->list[$i]->dt_txt), $date){
$regen += $fg;
}
**//But how do I get $date to be the following day**
}
echo $regen;
?>
I was able to solve it this way:
<?php
$nextWeek = time() + (24 * 60 * 60);
$morgen = date('Y-m-d', $nextWeek);
$url = "http://api.openweathermap.org/data/2.5/forecast?q=D%C3%BClmen,de&mode=json";
$response = file_get_contents($url);
$obj = json_decode($response);
$quote = 0;
for($i=0; $i < 14; $i++) {
if (strpos($obj->list[$i]->dt_txt, $morgen) !== false) {
$fg = $obj->list[$i]->clouds->all;
if($fg > 80) { $t = 1; }
$regen += $fg;
$quote++;
}
}
$regendiv = $regen / $quote;
?>
Probably not the prettiest way but it gets the job done.

PHP how to get value from multidimensional array?

I have an array in a class and want to obtain the 'Apple' key value ('iPhone').
I assume a for each loop needs to be used.
How would I go about doing this?
UPDATE: I also need to specify the customerType and productType key values.
class Products {
public function products_list() {
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr = array();
$productsArr[] = array(
'customerType' => 'national',
'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
}
}
I have created a function that you can more or less give it any product and it will return the key and value from the array
<?php
class Products
{
public function products_list()
{
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr[] = array(
'customerType' => 'national', 'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
echo $this->get_value($phoneType, $productsArr) .'<br>';
echo $this->get_value($customerType, $productsArr) .'<br>';
echo $this->get_value($productType, $productsArr) .'<br>';
}
function get_value($product, array $products)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($products), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $key => $value) {
if (is_string($value) && ($key == $product)) {
return 'key ->' . $key .' value ->'.$value;
}
}
return "";
}
}
$phone_products = new Products();
$phone_products->products_list();
To use it within the class just call
$this->get_value($phoneType, $productsArr);
from without the class call
$phone_products = new Products();
echo ($phone_products->get_value($phoneType, $productsArr));
//output: key ->Apple value ->iPhone
NB: $phoneType, $productsArr will either be defined the methods they are being used in or passed from other methods or define global variables within the class.
If you want single entry:
echo $productsArr[0]['productType']['phones']['Apple']."<br />";
If there are multiple data, you can use foreach:
foreach ($productsArr as $prod){
echo $prod['productType']['phones']['Apple']."<br />";
}
just try
foreach($productsArr[0]['productType']['phones'] as $phones){
echo $phones[$phoneType]; }
foreach($productsArr as $key1 => $data1 ){
if(is_array($data1))
foreach($data1 as $key2 => $data2 ){
if(is_array($data2))
foreach($data2 as $key3 => $data3 ){
if(array_key_exists('Apple', $data3)) {
echo $data3['Apple'] ."\n";
}
}
}
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

Setting a long Array . Missing data

I check every variable, but each one is echoing a verified result, so the problem is in the array. When I try to echo the full list of 56 values, I just get 11.
All variables are SET before, and i check for example if i echo $uno, i get a value of 12.. so why isnt that value on the array.
Here is my code..
$items = array(
$uno => "item1",
$dos => "item2",
$tres => "item3",
$cuatro => "item4",
$cinco => "item5",
$seis => "item6",
$siete => "item7",
$ocho => "item8",
$nueve => "item9",
$diez => "item10",
$once => "item11",
$doce => "item12",
$trece => "item13",
$catorce => "item14",
$quince => "item15",
$dieciseis => "item16",
$diecisiete => "item17",
$dieciocho => "item18",
$diecinueve => "item19",
$veinte => "item20",
$veintiuno => "item21",
$veintidos => "item22",
$veintitres => "item23",
$veinticuatro => "item24",
$veinticinco => "item25",
$veintiseis => "item26",
$veintisiete => "item27",
$veintiocho => "item28",
$veintinueve => "item29",
$treinta => "item30",
$treintayuno => "item31",
$treintaydos => "item32",
$treintaytres => "item33",
$treintaycuatro => "item34",
$treintaycinco => "item35",
$treintayseis => "item36",
$treintaysiete => "item37",
$treintayocho => "item38",
$treintaynueve => "item39",
$cuarenta => "item40",
$cuarentayuno => "item41",
$cuarentaydos => "item42",
$cuarentaytres => "item43",
$cuarentaycuatro => "item44",
$cuarentaycinco => "item45",
$cuarentayseis => "item46",
$cuarentaysiete => "item47",
$cuarentayocho => "item48",
$cuarentaynueve => "item49",
$cincuenta => "item50",
$cincuentayuno => "item51",
$cincuentaydos => "item52",
$cincuentaytres => "item53",
$cincuentaycuatro => "item54",
$cincuentaycinco => "item55",
$cincuentayseis => "item56",
);
The PHP CODE
<?PHP
echo "<strong>Original</strong><br />";
foreach($items as $k => $v){
echo $k . " = " . $v . "<br />";
}
asort($items);
echo "<strong>Ascending Sort</strong><br />";
foreach($items as $k => $v){
echo $k . " = " . $v . "<br />";
}
arsort($items);
echo "<strong>Descending Sort</strong><br />";
foreach($items as $k => $v){
echo $k . " = " . $v . "<br />";
}
?>
I get this as output..
Original
11 = item30
5 = item35
12 = item20
8 = item42
7 = item45
4 = item44
6 = item47
9 = item41
10 = item37
2 = item46
0 = item56
Ascending Sort
12 = item20
11 = item30
5 = item35
10 = item37
9 = item41
8 = item42
4 = item44
7 = item45
2 = item46
6 = item47
0 = item56
Descending Sort
0 = item56
6 = item47
2 = item46
7 = item45
4 = item44
8 = item42
9 = item41
10 = item37
5 = item35
11 = item30
12 = item20
Array keys must be unique. So, use itemNN for it.
$items = array(
"item1" => $uno,
"item2" => $dos,
"item3" => $tres,
...
Or even do not use string for keys
$items = array(
1 => $uno,
2 => $dos,
3 => $tres,
...
Or even like this
$items = array(
1 => $uno,
$dos,
$tres,
...

PHP: Merge arrays in loop

public function getCheckoutForm(){
$arr = array(
'cmd' => '_cart',
'business' => 'some#mail',
'no_shipping' => '1',
'upload' => '1',
'return' => 'url',
'cancel_return' => 'url1',
'no_note' => '1',
'currency_code' => 'url2',
'bn' => 'PP-BuyNowBF');
$cpt=1;
foreach($this->items as $item){
$arr1[] = array(
'item_number_'.$cpt.'' => $item['item_id'],
'item_name_'.$cpt.'' => $item['item_name'],
'quantity_'.$cpt.'' => $item['item_q'],
'amount_'.$cpt.'' => $item['item_price']
);
$cpt++;
}
return array_merge($arr,$arr1[0],$arr1[1]);
}
This returns array like that:
Array
(
[cmd] => _cart
[business] => some#mail
[no_shipping] => 1
[upload] => 1
[return] => url1
[cancel_return] =>url2
[no_note] => 1
[currency_code] => EUR
[bn] => PP-BuyNowBF
[item_number_1] => 28
[item_name_1] => item_name_1
[quantity_1] => 1
[amount_1] => 5
[item_number_2] => 27
[item_name_2] => item_name_2
[quantity_2] => 1
[amount_2] => 30
)
The problem is that in return $arr1[0] and $arr1[1] are hardcoded. And if in loop i have more than 2 arrays, lets say 0,1,2,3 ans so on, this code won't work. Any idea? Maybe my logic is compleatly wrong...
There's no need to create arrays in your loop - just add new keys directly to the first array:
public function getCheckoutForm(){
$arr = array(
'cmd' => '_cart',
'business' => 'some#mail',
'no_shipping' => '1',
'upload' => '1',
'return' => 'url',
'cancel_return' => 'url1',
'no_note' => '1',
'currency_code' => 'url2',
'bn' => 'PP-BuyNowBF'
);
$cpt=1;
foreach($this->items as $item){
$arr['item_number_'.$cpt] = $item['item_id'];
$arr['item_name_'.$cpt] = $item['item_name'];
$arr['quantity_'.$cpt] = $item['item_q'];
$arr['amount_'.$cpt] = $item['item_price'];
$cpt++;
}
return $arr;
}
I would probably do something like
$count = count($arr1);
for($i=0;$i<$count;$i++){
$arr = array_merge($arr,$arr1[$i]);
}
return $arr;
I hope, I understood, what you mean ^^
foreach ($i = 0, $n = count($arr1); $i < $n; $i++) {
$arr = array_merge($arr, $arr1[$i]);
}
return $arr;
You could do the merge in every iteration:
foreach($this->items as $item){
$temp_arr = array(
'item_number_'.$cpt.'' => $item['item_id'],
'item_name_'.$cpt.'' => $item['item_name'],
'quantity_'.$cpt.'' => $item['item_q'],
'amount_'.$cpt.'' => $item['item_price']
);
$arr = array_merge($arr,$temp_arr)
$cpt++;
}
which has the advantage that you could possibly get $temp_arr from a function,
or just add all the elements to one array:
foreach($this->items as $item){
$arr['item_number_'.$cpt.''] => $item['item_id'];
$arr['item_name_'.$cpt.''] => $item['item_name'];
$arr['quantity_'.$cpt.''] => $item['item_q'];
$arr['amount_'.$cpt.''] => $item['item_price'];
$cpt++;
}
do this
$count = count($data);
$sum = 1;
$arr = [];
for($i=0;$i<$count;$i++){
$temp = $arr;
if($i == $count - 1){
$sum = 0;
}
$arr = array_merge($temp,$data[$i + $sum]);
}
return $arr;

Categories