I need an out put like this.Can you please help me to sort this out?
a-1,2,4
b-3
for the following code:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
for($i=0;$i<count($paynum);$i++){
$paytypes = $paytype[$i];
$paynum = $payno[$i];
}
?>
Please Help
Just use array_unique, array_map and array_keys like this:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$uniqArr = array_unique($paytype); //Get all the unique value from array
foreach ($uniqArr as $value) {
echo $value . "-" . implode(",",array_map("matchVal",array_keys($paytype,$value)))."<br/>";
}
function matchVal($x) {
global $payno;
return $payno[$x];
}
Output:
a-1,2,4
b-3
Demo
You can try this:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$newArr = array();
for($i=0;$i<count($paytype);$i++){
if(!isset($newArr[$paytype[$i]])) {
$newArr[$paytype[$i]] = $payno[$i];
} else {
$newArr[$paytype[$i]] = $newArr[$paytype[$i]].",".$payno[$i];
}
}
print '<pre>';print_r($newArr);
?>
Output:
Array
(
[a] => 1,2,4
[b] => 3
)
Another alternative:-
Just use a simple foreach loop:-
$paytype = ['a','a','b','a'];
$payno= [1,2,3,4];
$res = [];
foreach($paytype as $k=>$v){
$res[$v] = empty($res[$v]) ? $payno[$k] : $res[$v].','.$payno[$k];
}
print '<pre>';print_r($res);
output:-
Array
(
[a] => 1,2,4
[b] => 3
)
If you want output
a-1,2,4
b-3
then add one additional foreach at the end.
foreach($res as $k=>$v){
echo "$k-$v<br>";
}
just use this code.
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$result = array();
for($i=0;$i<count($paytype);$i++){
$result[$paytype[$i]][] = $payno[$i];
}
$var = '';
foreach($result as $k => $v)
{
$var .= "{$k} - ". implode(",", $v) . "<br />";
}
print_r($var);
Result :
a - 1,2,4
b - 3
Related
I have an input string that has the following value:
"[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"
I want to convert this into a php array that looks something like this:
$date=2018-05-08;
$meal=1;
$option=17;
can someone help me please !
<?php
$data="[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$data=explode(',',$data);
foreach($data as $row){
preg_match_all('#\[(.*?)\]#', $row, $match);
$date=$match[1][0];
$meal=$match[1][1];
$option=$match[1][2];
}
This will store the values you need into the variables. I would suggest to store them in arrays and not variables so you can handle them outside of the foreach loop but that's up to you.
Simple parser for You
$arr1 = explode (",","[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"); // making array with elements like : [0] => "[2018-05-08][1][17]"
$arr2;
$i = 0;
foreach($arr1 as $item){
$temp = explode ("][",$item); // array with elements like [0] => "[2018-05-08", [1] => "1", [2] => "21]"
$arr2[$i]['date'] = substr( $temp[0], 1 ); // deleting first char( '[' )
$arr2[$i]['meal'] = $temp[1];
$arr2[$i]['option'] = substr($temp[2], 0, -1); // deleting last char( ']' )
$i++;
}
you cannot set array to variable .If you want convert string to array, i think my code example may help you:
$a= "[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$b= explode(",",$a );
foreach ($b as $key =>$value) {
$b[$key] = str_replace("[", " ", $b[$key]);
$b[$key] = str_replace("]", " ", $b[$key]);
$b[$key] =explode(" ",trim($b[$key]) );
}
print_r($b);
$results = array_map(
function ($res) {
$res = rtrim($res, ']');
$res = ltrim($res, '[');
return explode('][', $res);
},
explode(',', $yourString)
);
//get variables for first element of array
list($date, $meal, $option) = $results[0];
This question already has answers here:
Compare two array and get all differences
(2 answers)
Closed last year.
I want to get difference value from array and also want to compare that difference value is from which array.
First Array => Variable : $first_array
Array {607,608,609}
Second Array => Variable : $second_array
Array {607,608,609,610}
want to get output like Difference value : 610...... From Array :- $second_array
How can i get ? please help me ....
You can use array_diff()
$result=array_diff($first_array,$second_array);
print_r($result);
Try this :
$first_array=array(607,608,609);
$second_array=array(607,608,609,610);
$result=calculate_diff($second_array,$first_array);
print_r($result);
function calculate_diff($array1,$array2)
{
$diff = [];
$larger_array = $array2;
$smaller_array = $array1;
if(count($array1) > count($array2))
{
$larger_array = $array1;
$smaller_array = $array2;
}
foreach($larger_array as $ele)
{
if(!in_array($ele,$smaller_array))
{
$diff[] = $ele;
}
}
return $diff;
}
it will work
<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$result=array_diff($a,$b);
print_r($result);
?>
or else try this
<?php
$array2 = array(607,608,609);
$array1 = array(607,608,609,275);
foreach ($array1 as $value)
{
if(in_array($value, $array2))
{
$key = array_search($value, $array2);
$key1 = array_search($value, $array1);
unset($array2[$key]);
unset($array1[$key1]);
//echo "yes<br>";
}
}
$merge = array_merge($array1,$array2);
print_r($merge);
?>
Use array_diff
<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$res=array_diff($a,$b);
print_r($res); // output 610
?>
Try this:
$a = array(607,608,609,610);
$b = array(607,608,609);
$c = array_diff($a,$b);
print_r($c);
Try This:
$a1=array(607,608,609,610);
$a2=array(607,608,609);
$result=array_diff($a1,$a2);
print_r($result);
Output :- Array ( [3] => 610 )
Try this by merging them and then using array_diff, array_diff_assoc and array_unique.
https://3v4l.org/Z1vpe
$first = Array(607,608,609,610);
$second = Array(800,607,608,609);
$Fcount = count($first);
$arr = array_merge($first, $second);
$arrc= array_diff($arr, array_diff_assoc($arr, array_unique($arr)));
foreach ($arrc as $key => $value){
if($key < $Fcount){
echo "first array ". $value . "\n";
}else{
echo "second array " . $value . "\n";
}
}
Edited to add how to find which array the value is in. https://3v4l.org/W7rch
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue","r"=>"black");
$d = array_merge($a1,$a2);
output:array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"red","f"=>"green","g"=>"blue","r"=>"black")
$result=array_diff($d,array_intersect($a2,$a1));
print_r($result);
output:array("d"=>"yellow","r"=>"black");
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
I am trying to get my head around arrays.
The arrays should look like this:
$questions[$a] => array( [0] => No, comment1
[1] => Yes, comment2
[2] => No, comment3 )
$answer[$a] => array( [0] => No
[1] => Yes
[3] => No )
$comment[$a] => array( [0] => comment1
[1] => comment2
[3] => comment3 )
=========================================================================
SECOND EDIT: Need to execute this in the loop to create a third array -
if($answer[$a] == "Yes") { $display[$a] = "style='display:none'";
} else { $display[$a] = "style='display:block'"; }
This is what i have: (28th for minitech)
while ($a > $count)
{
if($count > 11) {
foreach($questions as $q) {
list($answer, $comments[]) = explode(',', $q);
if($answer === "Yes") {
$display[$a] = "style='display:none'";
} else {
$display[$a] = "style='display:block'";
}
$answers[] = $answer;
}
}
$a++;
}
If they are actually strings, explode works:
$answers = array();
$comments = array();
$display = array();
foreach(array_slice($questions, 11) as $question) {
list($answer, $comments[]) = explode(',', $question);
$display[] = $answer === 'Yes' ? 'style="display: none"' : 'style="display: block"';
$answers[] = $answer;
}
Here’s a demo!
Change your while loop to this
while ...
{
$parts = explode(',', $questions[$a]);
$answer[$a][] = trim($parts[0]);
$comment[$a][] = trim($parts[1]);
}
In your original code you were overwriting the $answer[$a] and $comment[$a] each time, not appending to the end of an array
$questions[$a] = array('Q1?' => 'A1', 'Q2?' => 'A2', 'Q3?' => 'A3');
foreach($questions[$a] as $key => $value)
{
$comment[$a][] = $key;
$answer[$a][] = $value;
}
This should work.
foreach ($questions[$a] as $key=>$value){
$temp = explode(',',$value);
$answer[$key] = $temp[0];
$comment[$key] = $temp[1];
}
$key will have 0,1,2 respectively. $value will have the values for each $question[$a](No,Comment1 ....)
Can't think of a funky one-liner, but this should do it:
foreach ($questions as $a => $entries) {
foreach ($entries as $k => $entry) {
$parts = array_map('trim', explode(',', $entry));
$answer[$a][$k] = $parts[0];
$comment[$a][$k] = $parts[1];
}
}
$questions = array( 0 => 'No,comment1',1 => 'Yes,comment2',2 => 'No,comment3' );
foreach($questions as $question)
{
$parts = explode(",",$question);
$answer[] = $parts[0];
$comment[] = $parts[1];
}
echo "<pre>";
print_r($answer);
print_r($comment);
Here is the right answer
foreach($questions as $key => $question){
foreach($question as $q => $data){
$data= explode(',',$data);
$comments[$key][$q] = $data[0];
$answer[$key][$q] = $data[1];
}
}
If the values in $questions are comma-separated strings you could use an array_walk function to populate your $answer and $comment arrays
$question = array(...); //array storing values as described
$answer = array();
$comment = array();
array_walk($question, function ($value, $key) use ($answer,$comment) {
$value_array = explode(',', $value);
$answer[$key] = $value_array[0];
$comment[$key] = $value_array[1];
});
Note that this is shown using an anonymous function (closure) which requires PHP >= 5.3.0. If you had a lower version of PHP, you would need to declare a named function, and declare $answer and $comment as globals in the function. I think this is a hacky approach (using globals like this) so if I was using PHP < 5.3 I would probably just use a foreach loop like other answers to your question propose.
Functions like array_walk, array_filter and similar functions where callbacks are used are often great places to leverage the flexibility provided by anonymous functions.
For example:
$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.
Here's my attempt:
<?php
$arr = array(3,5,2,5,3,9);
$temp_array = array();
foreach($arr as $val)
{
if(isset($temp_array[$val]))
{
$temp_array[$val] = $val;
}else{
$temp_array[$val] = 0;
}
}
foreach($temp_array as $val2)
{
if($val2 > 0)
{
echo $val2 . ', ';
}
}
?>
--
Output --
3, 5,
Try the following:
$arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset($arr[$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array($val,$arr)){
echo $val . " ";
}
}
Output:
3 5
Addition:
I guess that the reason you were asked to implement it yourself (without using built-in functions) was to avoid answers like:
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
$arrnew = array();
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($arr[$i]==$arr[$j])
{
$arrnew[]=$arr[$j];
}
}
}