String exploded twice array foreach loop - php

I have this code:
$sample = '5ml milk, 5ml water, 3pcs carrots';
echo $sample."</br>";
$first_slice = explode(',',$sample);
foreach($first_slice as $key => $value)
{
$second_slice[$key] = explode(' ',$value);
}
print_r($second_slice);
It does what i want, i need to separate 5ml milk from 5ml water and 3pcs carrots
from there i need to separate again 5ml from milk.
My question is, how do i select/echo only 5ml and milk as a single data.
The above code produces the result:
Array ( [0] => Array ( [0] => 5ml [1] => milk ) [1] => Array ( [0] =>
[1] => 5ml [2] => water ) [2] => Array ( [0] => [1] => 3pcs [2] =>
carrots ) )
Im quite confused on how do i select/echo since i exploded it twice means its an array inside an array. Please correct me if my understanding is wrong.
Additional question: I have to explode it thrice. Since my table has name,quantity,unit columns.
name for the ingredient name, quantity for the quantity, unit for the unit of measurement.
respectively [milk] [5] [ml]
I have done the same to make another array for separating measurement and quantity. But it cancels out the redundancy.
foreach($second_slice as $key=>$value)
{
$arr = explode('-',$value);
$third_slice[$arr[1]] = $arr[0];
}
The output is:
Array ( [ml] => 5 [pcs] => 3 )
There are 2 5ml's on the string. How do i not avoid it being taken out? since they are separate ingredients.

Currently, you have a multi-dimensional array. You can simpify this approach and flatten your array to one dimension. I suggest you modify your foreach loop as below:
foreach($first_slice as $key => $value)
{
$arr = explode(' ', trim($value));
$second_slice[$arr[1]] = $arr[0];
}
print_r($second_slice);
Produces the output:
Array
(
[milk] => 5ml
[water] => 5ml
[carrots] => 3pcs
)
Now, to get the quantity for any item, you can directly do echo $second_slice['item_name'].
And if you wanted to find the name of the quantity from the amount, you can use array_search():
$searchFor = '3pcs';
echo array_search($searchFor, $second_slice);
Outputs:
carrots
If there are multiple quantities with the same amount, the above method only returns the first. If you want to get all of them, you can use array_filter():
$result = array_filter($second_slice, function($elem) use ($searchFor){
return ($elem == $searchFor);
});
print_r($result);
Output:
Array
(
[milk] => 5ml
[water] => 5ml
)

You just want to output 5ml milk? Because if so, simply do the following:
echo $first_slice[0];

There is a hidden whitespace problem, but you can easily fix it with the following code by using trim:
$sample = '5ml milk, 5ml water, 3pcs carrots';
echo $sample."</br>";
$first_slice = explode(',',$sample);
foreach($first_slice as $key => $value)
{
$second_slice[$key] = explode(' ',trim($value));
}
print_r($second_slice);
which produces the following array:
Array
(
[0] => Array
(
[0] => 5ml
[1] => milk
)
[1] => Array
(
[0] => 5ml
[1] => water
)
[2] => Array
(
[0] => 3pcs
[1] => carrots
)
)

there are a few ways you can achieve this. Here is one way:
$sample = '5ml milk, 5ml water, 3pcs carrots';
$items = explode(",", $sample);
$final = array();
foreach($items as $i){
$value = explode(" ", trim($i));
$final[$value[1]] = $value[0];
}
echo "<pre>";
print_r($final);
echo "</pre>";

If you want to echo "5ml milk":
echo $second_slice[0][0] . " " . $second_slice[0][1];
echo "5ml water";
echo $second_slice[1][0] . " " . $second_slice[1][1];
echo "3pcs carrots";
echo $second_slice[2][0] . " " . $second_slice[2][1];

Related

Associate PHP index with another array

I have 3 explode statements:
$emails = explode(',', $row['email']);
$firstnames = explode(',', $row['first_name']);
$lastnames = explode(',', $row['last_name']);
each explode produces three (3) arrays:
//emails
Array
(
[0] => test123#example.com
[1] => lol123#example.com
[2] => haha#example.com
[3] => blahblah#example.com
)
//first name
Array
(
[0] => Bill
[1] => Jake
[2] => John
[3] => Bob
)
//last name
Array
(
[0] => Jones
[1] => Smith
[2] => Johnson
[3] => Bakers
)
I can get the one array easily like this: for example:
foreach ($emails as $email) {
echo $email;
}
That will echo out the emails. But I want to add $firstname and $lastname into it. for example, I want to echo:
test123#example.com Bill Jones
how can i do it?
foreach can assign a key and value if you use the appropriate syntax:
foreach ($emails as $key => $email) {
echo $email;
echo $firstnames[$key];
echo $lastnames[$key];
}
Next time, consult the manual: http://php.net/manual/en/control-structures.foreach.php as this is shown at the very top.
As Pyromonk pointed out, for is useful in situations where you have indexed arrays:
for ($i = 0, $n = count($emails); $i < $n; $i++) {
echo $emails[$i];
echo $firstnames[$i];
echo $lastnames[$i];
}

remove duplicates and move those that had duplicates to beginning of multi-dimensional array php

I'm creating a search function for a csv. With the result of my search I then want to remove duplicates and then move those that had duplicates to the beginning of the array.
Array
(
[0] => Array
(
[0] => COD 21
[1] => 4567
[2] => Robert Wahl
)
[1] => Array
(
[0] => RT 5
[1] => 1234
[2] => Robert Merrill
)
[2] => Array
(
[0] => XD 62
[1] => 1653
[2] => Robert Hill
)
[3] => Array
(
[0] => RT 5
[1] => 1234
[2] => Robert Merrill
)
)
I have a function that removes duplicates, but I'm not sure how to get it to move the values that have duplicates to the beginning of the array, and order them according to those with the most duplicates:
function arrayUnique($array) {
$aux_ini=array();
$result=array();
for($n=0;$n<count($array);$n++)
{
$aux_ini[]=serialize($array[$n]);
}
$mat=array_unique($aux_ini);
for($n=0;$n<count($array);$n++)
{
$result[]=unserialize($mat[$n]);
}
return $result;
}
Any and all help is appreciated.
function arrayUnique($array) {
// count values
$arr = array_count_values (array_map('serialize',$array));
// sort in desc order
arsort($arr);
// take keys and restore array
return array_map('unserialize',array_keys($arr));
}
function array_unique_ordered_by_duplicates($array)
{
//serialize inner arrays
$serialized = array_map('serialize', $array);
//create an array indexed by the serialized values, with all keys having a value of 0
$flipped = array_map(function($el){
return 0;
},array_flip($serialized));
//increment the count each time an element is encountered, thereby gicing duplicates a higher value
foreach($serialized as $v){
$flipped[$v]+=1;
}
//sort descending on the calculated value, putting the most duplicated items first
arsort($flipped);
//return unserialized, deduped, orded array
return array_map('unserialize',array_keys($flipped));
}
Note that splash58's is a more efficient version of the above, using php's array_count_values, and should be used instead
A little bit funky but I think the code is relatively easy to follow.
$csv = array(array('COD 21','4567','Robert Wahl')
,array('RT 5','1234','Robert Merrill')
,array('XD 62','1653','Robert Hill')
,array('RT 5','1234','Robert Merrill')
);
echo "Begin...<br>\n";
$serials = array();
$dupeqty = array();
foreach ($csv as $csvkey => $csvdata)
{
$dupekey = serialize($csvdata);
if ( !isset($serials[$dupekey]) )
$serials[$dupekey] = $csvkey;
if ( !isset($dupeqty[$dupekey]) )
$dupeqty[$dupekey] = 0;
$dupeqty[$dupekey]++;
}
arsort($dupeqty);
foreach ($dupeqty as $dupekey => $times)
echo $dupekey . " occurs $times times<br>\n";
flush();
echo "<br>\n";
echo "Accessing the original array...<br>\n";
foreach ($dupeqty as $dupekey => $times)
{
$data = $csv[$serials[$dupekey]];
echo '... data ' . $data[0] . ' ' . $data[1] . ' ' . $data[2] . "<br>\n";
}
Running it generates:
Begin...
a:3:{i:0;s:4:"RT 5";i:1;s:4:"1234";i:2;s:14:"Robert Merrill";} occurs 2 times
a:3:{i:0;s:5:"XD 62";i:1;s:4:"1653";i:2;s:11:"Robert Hill";} occurs 1 times
a:3:{i:0;s:6:"COD 21";i:1;s:4:"4567";i:2;s:11:"Robert Wahl";} occurs 1 times
Accessing the original array...
... data RT 5 1234 Robert Merrill
... data XD 62 1653 Robert Hill
... data COD 21 4567 Robert Wahl
try this,
function array_multidimensional($array)
{
$serialized = array_map('serialize', $array);
$array = array_unique($serialized);
return array_intersect_key($array, $unique);
}

How can I group my array into groups of 3 elements, sort them by the last element and display the elements?

I'm trying to display my array in groups of 3 elements, sorted by the last element of each group.
My array:
$info = array('goal','raul','80','foul','moneer','20','offside','ronaldo','60');
My expected output is:
1-foul moneer 20
2-offside ronaldo 60
3-goal raul 80
Sorted by the last value of the element groups.
I'm using foreach to display it:
$i = 0;
foreach($info as $key => $val) {
$i++;
echo $info[$key] . '<br>';
if ($i % 3 == 0){
echo "<br />";
}
Is this possible ? And if yes, how can I change my code to get my expected output?
This should work for you:
First we array_chunk() your array into chunks of 3 elements, so your array will have this structure:
Array
(
[0] => Array
(
[0] => goal
[1] => raul
[2] => 80
)
[1] => Array
(
[0] => foul
[1] => moneer
[2] => 20
)
[2] => Array
(
[0] => offside
[1] => ronaldo
[2] => 60
)
)
After this we sort it by the last value (here key 2), with usort() by simply comparing the values. Then at the end you can just loop through your array and display the data.
<?php
$info = array('goal','raul','80','foul','moneer','20','offside','ronaldo','60');
$arr = array_chunk($info, 3);
usort($arr, function($a, $b){
return $a[2] <=> $b[2];
});
foreach($arr as $k => $v)
echo ($k+1) . "-" . implode(" ", $v) . "<br>";
?>
output:
1-foul moneer 20
2-offside ronaldo 60
3-goal raul 80

Remove unset array containing specific string

I have the following array imported from a CSV:
Array
(
[0] => Array
(
[0] => QUARTERLY STATS;Q1/2011;Q2/2011;Q3/2011;Q4/2011;Q1/2012;Q2/2012;Q3/2012;Q4/2012;Q1/2013;Q2/2013;Q3/2013;Q4/2013;Q1/2014
)
[1] => Array
(
[0] => January;7500;8800;9500;10000;10500;11000;11500;12000;12500;13000;13420;13820;14200
)
[2] => Array
(
[0] => ;;17
[1] => 30%;8%;5
[2] => 30%;5%;4
[3] => 80%;4
[4] => 50%;4
[5] => 30%;4
[6] => 20%;4%;3
[7] => 20%;3%;2
[8] => 70%
)
[3] => Array
(
[0] => TOTAL;7500;8500;9500;11000;12500;11400;11800;13000;12500;13000;13420;13820;14200
)
[4] => Array
(
[0] => ;;17
[1] => 30%;7
[2] => 95%;5
[3] => 26%;5%;4
[4] => 76%;4
[5] => 55%;4
[6] => 35%;4
[7] => 17%;4%;3
[8] => 23%;2
[9] => 98%;2
[10] => 75%
)
So,
I would like to get rid of all arrays containing "% and TOTAL".
I thought to loop through and unset the matching case:
$remove ="TOTAL";
foreach ($csv as $key => $value){
if (in_array($remove,$value[$key])){
unset($value[$key]);
}
}
This is the error I got:
Warning: in_array() expects parameter 2 to be array, null given
My PHP Version 5.3.10
Would you do it that way or would you use the array_filter?
I am browsing since 2 hours the forum but I could not find any hint helping me out.
Cheers.
You can try by preg_replace for removing TOTAL & %. If you want to remove the element from array then use unset & finally use array_filter for removing null elements.
$newArr = array();
foreach($arr as $key=>$value){
foreach($value as $k=>$v){
$newArr[$key][$k] = preg_replace('/(TOTAL)|(%)/', '', $v); //for removing TOTAL & %
unset($arr[$key][$k]); //for unset the array elements that contains TOTAL & %
}
}
//Output by replacement
print '<pre>';
print_r($newArr);
print '</pre>';
//output after using unset
print '<pre>';
print_r(array_filter($arr));
print '</pre>';
In your case:
foreach ($csv as $subArray)
{
for ($i = 0, $len = count($subArray); $i < $len; $i++)
{
if (strpos($subArray[$i], $remove) !== false)
unset($subArray[$i])
}
}
Comments:
strict comparasion for strpos, if we use !=, then 0 position would be equals to false.
inner loop is "for-loop" bevause it's better to avoid changing content of array inside foreach.
$arr[][] = ("QUARTERLY STATS;Q1/2011;Q2/2011;Q3/2011;Q4/2011;Q1/2012;Q2/2012;Q3/2012;Q4/2012;Q1/2013;Q2/2013;Q3/2013;Q4/2013;Q1/2014");
$arr[][] = ("January;7500;8800;9500;10000;10500;11000;11500;12000;12500;13000;13420;13820;14200");
$arr[] = array(";;17","30%;8%;5","30%;5%;4","80%;4","50%;4","30%;4","20%;4%;3","20%;3%;2","70%");
$arr[][] = ("TOTAL;7500;8500;9500;11000;12500;11400;11800;13000;12500;13000;13420;13820;14200");
$arr[] = array("30%;7","95%;5","26%;5%;4","76%;4","55%;4","35%;4","17%;4%;3","23%;2","98%;2","75%");
$newArr = array();
foreach($arr as $key=>$value) {
foreach($value as $k=>$v) {
$newArr[$key][$k] = preg_replace('/(TOTAL)|(%)/', '', $v); //for removing TOTAL & %
unset($arr[$key][$k]); //for unset the array elements that contains TOTAL & %
}
unset($arr[$key]); // IT does not unset ARR[2] ARR[3] and ARR[4] containing TOTAL & %
}
Output by replacement
print '<pre>';
print_r($newArr);
print '</pre>';
Output after using unset
print '<pre>';
print_r(array_filter($arr));
print '</pre>';
I did create exactly the same ARRAY as imported from CSV.
unset does not unset ARRAY2,3,4 which is containing TOTAL AND %.
unset does not unset ARRAY2,3,4 which is containing TOTAL AND %.

preg_replace Multiple strings in array using foreach loop

$message_detected = "#A# #B#";
Array ( [0] => Array ( [0] => 923126812536 [1] => Mudassar [2] => Kasur )
[1] => Array ( [0] => 923006542399 [1] => Zubair [2] => Lahore ) );
There are 2 arrays
foreach ($array as $new){
$find = array('/#A#/', '/#B#/', '/#C#/', '/#D#/', '/#E#/', '/#F#/', '/#G#/', '/#H#/', '/#I#/', '/#J#/', '/#K#/', '/#L#/', '/#M#/', '/#N#/', '/#O#/', '/#P#/', '/#Q#/', '/#R#/', '/#S#/', '/#T#/', '/#U#/', '/#V#/', '/#W#/', '/#X#/', '/#Y#/', '/#Z#/');//26
$replace = array($new[1], $new[2], $new[3], $new[4], $new[5], $new[6], $new[7], $new[8], $new[9], $new[10], $new[11], $new[12], $new[13], $new[14], $new[15], $new[16], $new[17], $new[18], $new[19], $new[20], $new[21], $new[22], $new[23], $new[24], $new[25], $new[26]);
$message_detected = preg_replace($find, $replace, $message_detected);
//Message should be change each time despit of only first
echo "Messsage :". $message_detected."</br></br></br></br>";
}
Result Should be
Messsage :Mudassar Kasur
Messsage :Zubair Lahore
But it shows
Messsage :Mudassar Kasur
Messsage :Mudassar Kasur
Please Guide me where i am wrong . And how to get Required Result
You're overwriting your variable on each loop. It should be a different one:
$template = "#A# #B# #C#";
$values = array (
array ( 923126812536, 'Mudassar', 'Kasur'),
array ( 923006542399, 'Zubair', 'Lahore'),
);
$vars = array('#A#', '#B#','#C#','#D#');
foreach($values as $lst) {
$result = str_replace($vars, $lst, $template);
echo $result, "\n";
}
(I changed variable names for readability).

Categories