PHP: checking array to see if values match, display those values - php

I am generating an array from a while loop, and I would like to eventually use this array to display data.
while($row = $database->fetch(PDO::FETCH_ASSOC)
{
$value_1 = $row['value_1'];
$value_2 = $row['value_2'];
$data[] = array("value_1"=>$value_1,"value_2"=>$value_2);
}
so the $data[] would display using print_r I get something like this:
Array
(
[0] => Array
(
[value_1] => Hello World
[value_2] => venus
)
[1] => Array
(
[value_1] => Hello World
[value_2] => pluto
)
[2] => Array
(
[value_1] => Hello Moon
[value_2] => Halloween
)
)
My question is, how would I do a foreach loop or display such a way where if I wanted to get all data, but consolidate the same values?
Ex:
Hello World to venus pluto
Hello Moon to Halloween
I know those sentences doesn't make sense, but as you can see Hello World would be consolidated and I would need to add an " to" in between value_1 and value_2
Hope my question is understandable.
Thanks!

Try something like this. (Not Tested)
$match = array();
foreach($data as $d) {
if (isset($match[$d['value_1']])) {
$match[$d['value_1']] = $match[$d['value_1']].' '.$d['value_2'] ;
} else {
$match[$d['value_1']] = $d['value_1']. ' to '. $d['value_2'];
}
}
print_r($match);

I think for this first you need to create new array as follows:
$new_array = array();
//consider your original array is $data
foreach($data as $row){
if (array_key_exists($row['value_1'], $new_array)) {
$new_array[$row['value_1']] = $new_array[$row['value_1']]. " ".
$row['value_2'];
}
else {
$new_array[$row['value_1']] = $row['value_2'];
}
}
Then display it by iterating:
foreach($new_array as $key => $value){
echo $key ."to". $value;
}

foreach($data as $d) {
echo $d['value_1'], ' to ', $d['value_2']; // this is if you want to echo the content
// this code is to insert 'to' in the middle of value_1 and value_2
$value_2 = $d['value_2'];
unset($d['value_2']);
array_push($d, "to", $value_2);
unset($value_2);
}
Also you don't need to assign the $row value to another value:
$value_1 = $row['value_1']; // remove this
$value_2 = $row['value_2']; // remove this
$data[] = array("value_1" => $row['value_1'], "value_2" => $row['value_2']);

Related

How to group array and mount select

I really need your help! How can I do to group the array results and assemble select.
Database
Image Database
PHP
<?php
$rsPA = $mysqli->query("SELECT * FROM provas_agendadas WHERE status = 'A' ");
foreach ($rsPA as $key => $rsRowPA){
$dis1[] = explode("," , $rsRowPA['disciplinas']);
}
echo '<pre>';print_r($dis1);echo '</pre>';
?>
Result:
Array
(
[0] => Array
(
[0] => EJA-1
)
[1] => Array
(
[0] => EJA-1
[1] => EJA-5
[2] => TTI-1
)
)
Expilando: From the result of the array, I will only get the number after the -, Ex: EJA-1, I only need 1, which is the ID of the discipline table.
End result you would like
Image select
I thank everyone who can help me.
You could perform an additional for loop, and explode each element on - and take the last part:
<?php
$rsPA = $mysqli->query("SELECT * FROM provas_agendadas WHERE status = 'A' ");
foreach ($rsPA as $key => $rsRowPA){
$temp = explode("," , $rsRowPA['disciplinas']);
foreach($temp as $elem){
$number = explode('-',$elem);
$number = end($number);
$numbers[] = $number;
}
}
$dis1 = array_count_values($numbers);
echo '<pre>';print_r($dis1);echo '</pre>';
?>

Conversion of an array from one form to another

I have an array.
Array
(
[0] => 1_4
[1] => 1_1
[2] => 1_2
[3] => 2_3
[4] => 2_5
)
I want to convert it to
Array
(
[1] => Array (4,1,2)
[2] => Array (3,5)
)
Can any1 help me in this? The new keys (1 and 2) are the distinct values from 1st part of array before _.
If the underscore will always be the unique split you could explode on underscore and append results to a new array.
$before = ['1_4','1_1','1_2','2_3','2_5'];
$after = [];
foreach ($before as $entry) {
$index = explode('_',$entry);
$after[$index[0]][] = $index[1];
}
return $after;
Quick and dirty...
foreach($array as $value){ // Loop your current array
$arr = substr($value,0); // Get the character before _, 1 or 2
$val = substr($value,2); // Get character after _, 1,2,3,4 or 5
if($arr == 1){ // if 1_, put into first new array
$newArray[0][] = $val;
}else{
$newArray[1][] = $val; // Put into second array else
}
}
print_r($newArray);
Maybe try something like this?
foreach ($array as $element( {
$kv_pair = explode("_", $element, 2);
if (array_key_exists($kv_pair[0])) {
array_push($new_array[$kv_pair[0]], $kv_pair[1]);
} else {
$new_array[$kv_pair[0]] = [$kv_pair[1]];
}
}

How to find unique values in array

Here i want to find unique values,so i am writing code like this but i can't get answer,for me don't want to array format.i want only string
<?php
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$unique_array = array(); // unique array
$duplicate_array = array(); // duplicate array
foreach ($array as $key=>$value){
if(!in_array($value,$unique_array)){
$unique_array[$key] = $value;
}else{
$duplicate_array[$key] = $value;
}
}
echo "unique values are:-<br/>";
echo "<pre/>";print_r($unique_array);
echo "duplicate values are:-<br/>";
echo "<pre/>";print_r($duplicate_array);
?>
You can use array_unique() in single line like below:-
<?php
$unique_array = array_unique($array); // get unique value from initial array
echo "<pre/>";print_r($unique_array); // print unique values array
?>
Output:- https://eval.in/601260
Reference:- http://php.net/manual/en/function.array-unique.php
If you want in string format:-
echo implode(',',$final_array);
Output:-https://eval.in/601261
The way you want is here:-
https://eval.in/601263
OR
https://eval.in/601279
I am baffled by your selection as the accepted answer -- I can't imagine how it can possibly satisfy your requirements.
array_count_values() has been available since PHP4, so that is the hero to call upon here.
Code: (Demo)
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$counts = array_count_values($array); // since php4
foreach ($counts as $value => $count) {
if ($count == 1) {
$uniques[] = $value;
} else {
$duplicates[] = $value;
}
}
echo "unique values: " , implode(", ", $uniques) , "\n";
echo "duplicate values: " , implode(", ", $duplicates);
Output:
unique values: raja, mahi
duplicate values: kani, yuvi
To get unique values from array use array_unique():
$array = array(1,2,1,5,10,5,10,7,9,1) ;
array_unique($array);
print_r(array_unique($array));
Output:
Array
(
[0] => 1
[1] => 2
[3] => 5
[4] => 10
[7] => 7
[8] => 9
)
And to get duplicated values in array use array_count_values():
$array = array(1,2,1,5,10,5,10,7,9,1) ;
print_r(array_count_values($array));
Output:
Array
(
[1] => 3 // 1 is duplicated value as it occurrence is 3 times
[2] => 1
[5] => 2 // 5 is duplicated value as it occurrence is 3 times
[10] => 2 // 10 is duplicated value as it occurrence is 3 times
[7] => 1
[9] => 1
)
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1)); // will print unique values
echo "<br>";
arr_count_val($arr1); // will print array with duplicate values
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
function arr_count_val($arr) {
$uni_array = arr_unique($arr1);
$count = 0;
foreach($uni_array as $n1) {
foreach($arr as $n1) {
if($n1 == $n2) {
$count++;
}
}
echo "$n1"." => "."$count"."<br>";
$count=0;
}
}
?>

How to get unique value in multidimensional array

I have done a lot of looking around on the overflow, and on google, but none of the results works for my specific case.
I have a placeholder array called $holder, values as follows:
Array (
[0] => Array (
[id] => 1
[pid] => 121
[uuid] => 1
)
[1] => Array (
[id] => 2
[pid] => 13
[uuid] => 1
)
[2] => Array (
[id] => 5
[pid] => 121
[uuid] => 1
)
)
I am trying to pull out distinct/unique values from this multidimensional array. The end result I would like is either a variable containing (13,121), or (preferrably) an array as follows:
Array(
[0] => 13
[1] => 121
)
Again I've tried serializing and such, but don't quite understand how that works when operating with a single key in each array.
I tried to be as clear as possible. I hope it makes sense...
Seems pretty simple: extract all pid values into their own array, run it through array_unique:
$uniquePids = array_unique(array_map(function ($i) { return $i['pid']; }, $holder));
The same thing in longhand:
$pids = array();
foreach ($holder as $h) {
$pids[] = $h['pid'];
}
$uniquePids = array_unique($pids);
In php >= 5.5 you can use array_column:
array_unique(array_column($holder, 'pid'));
try this
foreach($arr as $key => $val) {
$new_arr[] = $val['pid'];
}
$uniq_arr = array_unique($new_arr);
Just iterate over it and apply an array_unique on the result:
foreach($holder as $yourValues){
$pids[] = $yourValues['pid'];
}
$yourUniquePids = array_unique($pids);
Assuming your array is called $holder:
$unique = array();
foreach( $holder as $h )
if( ! in_array($h, $unique ) )
$unique[] = $h;
is a slightly more efficient way than via array_unique, I believe. May be the same.
$uniquearray = [];
for($i=0;$i<count($assocarray);$i++){
if(!in_array($assocarray[$i]['KEY'],$uniquearray)){
$uniquearray[$i]= $assocarray[$i]['KEY'];
}
}
Hi Please try code given below for get unique values and then sort that values
<?php
$sort_arr = unique_sort($holder, 'pid');
echo "<pre>";
print_r($sort_arr);
echo"</pre>";
/*function for get unique value then sort them*/
function unique_sort($arrs, $id) {
$unique_arr = array();
foreach ($arrs AS $arr) {
if (!in_array($arr[$id], $unique_arr)) {
$unique_arr[] = $arr[$id];
}
}
sort($unique_arr);
return $unique_arr;
}
thanks
fo my situation i use this method
//get some data from db to array
while ($row = mysqli_fetch_assoc($query)){
$data[] = $row;
}
//display unique value
echo "<table>";
$uniq = array();
foreach ($data as $row) {
if(!in_array($row['path'], $uniq)) {
$uniq[] = $row['path'];
echo "<tr>";
echo "<td>";
echo $row['path'];
echo "</td>";
echo "<td>";
echo $row['relationship_id'];
echo "</td>";
echo "</tr>";
}
}
echo "</table>";

PHP explode and put into array

I have this line of string
Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie
the : (colon) is the separator for the main topic, and the | is the separator for the different type of sub topics.
I tried to explode it out and put it into array, I need the result to be something like this to be displayed in a drop down menu:-
Fruits
banana
apple
orange
Food
fries
sausages
$result=explode(":",$data);
foreach($result as $res) {
$sub_res[]=explode("-",$res);
}
foreach($sub_res as $sub) {
//echo $sub[1]."<br>"; Over here, I can get the strings of [0]=>banana|apple|orange, [1]=>sausages|fries,
// I explode it again to get each items
$items[]=explode("|",$sub[1]);
$mainCategory[]=$sub[0]; // This is ([0]=>Fruits, ]1]=>Food, [2]=>dessert
// How do I assign the $items into respective categories?
}
Thanks!
You can do:
$result=explode(":",$data);
foreach($result as $res) {
$sub = explode("-",$res);
$mainCategory[$sub[0]] = explode("|",$sub[1]);
}
Working link
Code:
$data = "Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie";
foreach(explode(":",$data) as $res) { // explode by ":"
$cat = explode("-",$res); // explode by "-"
$ilovefood[$cat[0]] = explode("|",$cat[1]); // explode by "|"
}
print_r($ilovefood);
//Returns : Array ( [Fruits] => Array ( [0] => banana [1] => apple [2] => orange ) [Food] => Array ( [0] => fries [1] => sausages ) [Desserts] => Array ( [0] => ice cream [1] => apple pie ) )
foreach($ilovefood as $type=>$yum){
echo "$type:<select>";
foreach($yum as $tasty){
echo "<option>$tasty</option>";
}
echo "</select>";
}
Updated to reflect the drop-down addition. Looks like I just did your homework, though I'll leave it up to you to combine all the into one foreach loop.
I'd propose an arguably more readable version of codeaddicts' answer
$str = "Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie";
$topics = array();
foreach (explode(':', $str) as $topic) {
list($name, $items) = explode('-', $topic);
$topics[$name] = explode('|', $items);
}

Categories