How to use foreach loop using two array to get result - php

I have two array as follow
[1]=>Array(
[ingrediant]=>Array(
[A]=>Chicken [C]=>TomatoJuice
)
[price]=> 100
)
[2]=>Array(
[ingrediant]=>Array(
[A]=>Pork [C]=>LimeJuice
)
[price]=> 50
)
[3]=>Array(
[ingrediant]=>Array(
[B]=>Chille [C]=>TomatoJuice
)
[price]=>100
)
)
And
Array([A]=>Array([name]=>meat [code]=>001)
[B]=>Array([name]=>Vegetable [code]=>002)
[C]=>Array([name]=>Juice [code]=>003)
)
First Array Show the food combo and Second Array Show Type of the Ingredients
For example,
Chicken+tomatojuice Combo
Chicken is meat and tomatojuice is juice.
I would like to get the result as follow group by juice.
>Tomatojuice
-Meat:Chicken, price:100
-Vegetable:Chille, price:100
>LimeJuice
-Meat:Pork, price:100
How can I get these results by using php foreach. I have tried several time.Not Okay at all.

This code should solve your problem
Based on your array declaration :
$food_combo[] = array(
'ingrediant'=> array(
'A' => 'Chicken',
'C' => 'TomatoJuice'
),
'price'=>100
);
$food_combo[] = array(
'ingrediant'=> array(
'A' => 'Pork',
'C' => 'LimeJuice'
),
'price'=>50
);
$food_combo[] = array(
'ingrediant'=> array(
'B' => 'Chille',
'C' => 'TomatoJuice'
),
'price'=>100
);
$types['A'] = array('name'=>'meat','code'=>'001');
$types['B'] = array('name'=>'vegetable','code'=>'002');
$types['C'] = array('name'=>'juice','code'=>'003');
Here is the algorithmic :
$group_by = 'C';
$combo = $output = array();
foreach($food_combo as $food){
//array("A","B"....);
$missed = array_diff(
array_keys($food['ingrediant']),
isset($combo[$food['ingrediant'][$group_by]]) ?
$combo[$food['ingrediant'][$group_by]] : array()
);
if(count($missed)){
//remove initial group define as key
foreach(array_diff($missed,array($group_by)) as $type_code)
$output[$food['ingrediant'][$group_by]][] =
$types[$type_code]['name'] .
':' . $food['ingrediant'][$type_code] .
',' . 'price:' . $food['price'];
}
}
print_r($output);

Related

Insert array into a single field in a MYSQL database

I am creating a SELECT drown down list, I would like to have it loaded in 1 of 2 ways.
First way is pulling data from database with ID, name, and Value - This way will be loaded from other pages.
Second way, I would like to load from a Single line in the database with Name and Value. But I want to have that value be loaded with an array.
How do I load that array into the database?
$name = 'name';
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
$SQL = 'INSERT INTO table_name (name, value) VALUES ($name,$value);
I expect when I run the SELECT * from table_name WHERE name = "name" to use that array in the value field right away.
With what "RakeshJakhar" said, to use the implode and explode onto $value
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
print_r( $value );
echo "<br />";
echo implode( ",", $value );
echo "<br />";
$implode = implode( ",", $value );
$explode = explode( ',', $implode );
print_r( $explode );
Results:
Array ( [red] => Red [blue] => Blue )
Red,Blue
Array ( [0] => Red [1] => Blue )
You can use json_encode and json_decode
$value = array( 'red' => 'Red', 'blue' => 'Blue' );
$column = json_encode($value);
So the inserted value {"red":"Red","blue":"Blue"}
When you are fetching value use json_decode
$values = json_decode($column,true);

substitute the elements of an array coditionally

I need to create an array of prices. So I've an array of base prices and an array of promotional prices, if the promotional price is lower than the base price, I put it in the new array of prices. For this purpose I wrote this code:
<?php
$array_base_prices = array(
array('id'=>1, 'price'=>10),
array('id'=>2, 'price'=>2),
array('id'=>3, 'price'=>30),
array('id'=>4, 'price'=>40)
);
$array_promo = array(
array('id'=>1, 'price'=>20),
array('id'=>2, 'price'=>5),
array('id'=>3, 'price'=>2)
);
$base_prices_with_promo = array();
foreach ( $array_base_prices as $j => $u ) {
foreach ( $array_promo as $k => $v ) {
if ( ($v['id'] == $u['id']) && $u['price'] < $v['price']) {
$base_prices_with_promo[$j]['id'] = $array_base_prices[$j]['id'];
$base_prices_with_promo[$j]['price'] = $array_base_prices[$j]['price'];
}
if ( ($v['id'] == $u['id']) && $u['price'] > $v['price']) {
$base_prices_with_promo[$j]['id'] = $array_promo[$k]['id'];
$base_prices_with_promo[$j]['price'] = $array_promo[$k]['price'];
}
}
}
$base_prices_with_promo = array_replace( $array_base_prices, $base_prices_with_promo );
echo "<pre>";
print_r($base_prices_with_promo);
echo "</pre>";
?>
and it works fine, but I think that the if conditions into the nested foreach are a little messy. I'm working with multidimensional, associative arrays, very big with a lot of keys. So I'm wondering if there is any better alternative to achieve the same result.
There's really not enough context for me to be sure that this is an option for you, but from your little example I would change the array declaration to this:
$array_base_prices = array(
1 => 10,
2 => 2,
3 => 30,
4 => 40
);
$array_promo = array(
1 => 20,
2 => 5,
3 => 2
);
Or use an array if you need to store more data than just price:
$array_base_prices = array(
1 => array("price" => 10, "something_else" => null)
);
The point is to have the id as index of the parent array. Then your nested loops turn to this:
foreach ($array_base_prices as $id => $base_price) {
$base_prices_with_promo[$id] = $base_price;
if (isset($array_promo[$id]) && $base_price > $array_promo[$id]) {
$base_prices_with_promo[$id] = $array_promo[$id];
}
}

How do I convert a string of an array to an array in PHP?

This seems like a simple task, but I haven't been able to find a way to do this. I have an output of data stored as a string like this:
$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";
What I simply need to do is convert it to this array:
$arrData = array('first' => "$first", 'middle' => "$middle", 'last' => "$last");
The closest I have been able to get is this shown below with print_r results:
$Data = explode(',', $rawData);
Array
(
[0] => 'first' => '$first'
[1] => 'middle' => '$middle'
[2] => 'last' => '$last'
)
What I need is this:
Array
(
[first] => $first
[middle] => $middle
[last] => $last
)
Must be something very easy I have overlooked. Please help.
Depending on where you get the string from, you may use eval. It's highly recommended to not use this function, whenever the contents of that string may be influenced directly or indirectly by a user, see hint at http://php.net/manual/en/function.eval.php. And it must contain valid PHP syntax, thus putting it into a try/catch block is necessary:
$evalArray = false;
$first = 'a';
$middle = 'b';
$last = 'c';
$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";
try {
$evalArray = eval($rawData);
} catch ( $e )
{
echo "parsing failed " . $e
}
print_r($evalArray );
This does what you want ( i think ), even if its not pretty
<?php
$arr = array();
$first = 'one';
$middle = 'two';
$last = 'three';
$rawData = "array('first' => '$first', 'middle' => '$middle', 'last' => '$last')";
$arrData = explode( ',', ( str_replace( array( 'array(\'', '=>', '\')', '\'' ), array( '', '%##%', '', '' ), $rawData ) ) );
foreach( $arrData as $val ) {
$v = explode( '%##%', $val );
$arr[trim($v[0])] = trim($v[1]);
}
echo '<pre>' . print_r( $arr, true ) . '</pre>';
?>

How to parse a string into a multidimensional array when the separator is optional

I have a string ($c) that contains a comma-separated list of settings. Some settings are stand-alone, while others require a sub-setting that is separated by an equal sign.
Example:
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,date";
I need to parse this string into a multidimensional array ($columns) that outputs like this:
$columns = array(
[0] => array( 'title', '' ),
[1] => array( 'author', '' ),
[2] => array( 'tax', 'taxonomy_A' ),
[3] => array( 'tax', 'taxonomy_B' ),
[4] => array( 'date', '' )
)
I have tried this:
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,meta=custom_field_key";
$c = explode( ',', $c );
$columns = array( explode( '=', $c ) );
But that just returns this:
$columns = array(
[0] => array( 'Array' )
)
What am I missing here? Should the second explode be replaced with a different function?
Thanks in advance!
foreach(explode(',', "title,author,tax=taxonomy_A,tax=taxonomy_B,date") as $item)
$items[] = array_pad(explode('=', $item), 2, '');
You'll need to loop after the first explode to do the second one:
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,meta=custom_field_key";
$arr = explode( ',', $c );
$result = array();
foreach($arr as $a) {
array_push($result, explode('=', $a));
}
print_r($result);
In your code, you don't apply the second explode to each element of the array, but just once to the whole array object. This causes the array to be transformed into the string "Array", which is then run through explode() and results in your output.
Instead you could use array_map() (PHP docu):
function filterArr( $value ) {
return explode( '=', $value )
}
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,meta=custom_field_key";
$c = explode( ',', $c );
$c = array_map( "filterArr", $c );

summarise php array into treeview

Array
(
[00000000017] => Array
(
[00000000018] => Array
(
[00000000035] => I-0SAYHADW4JJA
[00000000038] => I-RF10EHE25KY0
[00000000039] => I-8MG3B1GT406F
)
[00000000019] => I-7GM4G5N3SDJL
)
[00000000025] => Array
(
[00000000011] => I-HT34P06WNMGJ
[00000000029] => I-U5KKT1H8J39W
)
[00000000040] => I-GX43V2WP9KPD
[00000000048] => I-XM526USFJAH9
[00000000052] => I-M414RK3H987U
[00000000055] => I-GABD4G13WHX7
)
I have the above array and i want to create a treeview display..
any recommendation ?
I guess i have to elaborate furthe on my question..
I want to store those array according to the level of array..
Example , I want something look like this :
[level_1]=> 00000000017,00000000025,00000000040, 00000000048, 00000000052
[level_2]=> 00000000018,00000000019, 00000000011, 00000000029
[level_3]=> 00000000035, 00000000038, 00000000039
You want a modified breadth-first search. This has the correct results for your sample structure:
<?php
function BFTraverse(&$tree = NULL, $depth = 0)
{
if (empty($tree))
return FALSE;
$keys = array_keys($tree);
$struct["lvl_$depth"] = $keys;
foreach ($keys as $key)
{
if (is_array($tree[$key]))
{
$struct = array_merge_recursive($struct, BFTraverse($tree[$key], $depth + 1));
}
}
return $struct;
}
$data = array
('00000000017' => array
(
'00000000018' => array
(
'00000000035' => 'I-0SAYHADW4JJA',
'00000000038' => 'I-RF10EHE25KY0',
'00000000039' => 'I-8MG3B1GT406F'
),
'00000000019' => 'I-7GM4G5N3SDJL'
),
'00000000025' => array
(
'00000000011' => 'I-HT34P06WNMGJ',
'00000000029' => 'I-U5KKT1H8J39W'
),
'00000000040' => 'I-GX43V2WP9KPD',
'00000000048' => 'I-XM526USFJAH9',
'00000000052' => 'I-M414RK3H987U',
'00000000055' => 'I-GABD4G13WHX7'
);
$var = BFTraverse($data);
$i = 0;
foreach ($var as $level)
echo "Level " . ++$i . ': ' . implode(', ', $level) . "\n";
?>
The output is:
Level 1: 00000000017, 00000000025, 00000000040, 00000000048, 00000000052, 00000000055
Level 2: 00000000018, 00000000019, 00000000011, 00000000029
Level 3: 00000000035, 00000000038, 00000000039
edit: Modified in the sense that you want the keys and not the node values.
I ran into the same problem recently and this article by Kevin van Zonneveld helped me out.
Basically you have to use a recursive function. Check out the article, it's what you need!

Categories