How to get unique value in multidimensional array - php

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>";

Related

print array value in php

I have a php array value but i don't know how to print it. there is my php code
$json = array();
if($sql->num_rows > 0){
while($result = $sql->fetch_assoc()) {
$json[] = $result;
}
}
And here is my array value
Array
(
[0] => Array
(
[locationid] => 1
[locationname] => Anantapur
[locationvalue] => 1.1
)
[1] => Array
(
[locationid] => 2
[locationname] => Guntakal
[locationvalue] => 1.2
)
[2] => Array
(
[locationid] => 4
[locationname] => Guntur
[locationvalue] => 1.3
)
)
I'm Trying like
echo $json['locationname'];
But It's Not working please help me
You need to loop through your array first. Try foreach
foreach($json as $j){
echo $j['locationname'];
}
You have not need to make a new array after get the result. you can print your value within the loop
if($sql->num_rows > 0){
while($result = $sql->fetch_assoc()) {
echo $result['locationaname'];
}
}
The array you created is associative array. For loo through these type of arrays requires foreach. Visit http://php.net/manual/en/control-structures.foreach.php
foreach($json AS $key =>$value){
echo $value['locationname'];
}
You can directly print the value of location, instead of creating a new array, unless you need it further.
if($sql->num_rows > 0){
while($result = $sql->fetch_assoc()) {
echo $result['locationname'];
}
}
if you want to have $json, which is an associative array, you need to get into it, looping through it.
foreach($json as $key => $value){
echo $value['locationname'];
}
If you want json string try this:
echo json_encode($json);
after your loop.

How to Print associative array in foreach

I have an associative array in php, how can i print it with php foreach loop
Array( [0] => Array ( [fb_user_id] => 100000058716604 [accept_status] => 1 ) [1] => Array ( [fb_user_id] => 100004069844270 [accept_status] => 1 ) )
Tried this but no success, i want to print the fb_user_id
foreach($resulttotal[fb_user_id] as $value)
{
echo $value;
}
Please help me, Thanks
You doing incorrectly, It will be like:
foreach($resulttotal as $value)
{
echo $value['fb_user_id'];
}
It would make more sense to use a regular for loop.
for($i = 0; $i < count($resulttotal); $i++) {
$row = & $resulttotal[$i];
echo $row['fb_user_id'];
}
But this could be a foreach too.
foreach($resulttoal as $key) {
echo $key['fb_user_id']
}

JSON array in html table

I have a json array, looks like:
Array (
[0] => Array
(
[k1] => aaa
[k2] => aaa
[kTypes] => Array
(
[ktype1] => Array
(
[desc] => asd
)
[ktype2] => Array
(
[desc] => asd
)
)
)
And I try to get the desc values inside ktypes, tried this:
$items = $myArray;
// echo "<pre>";
// print_r($items);
// echo "</pre>";
echo '<table>';
echo '<tr><th>k1</th><th>k2</th><th>ktype1</th><th>ktype2</th></tr>';
foreach($items as $item)
{
echo "<tr><td>$item[k1]</td><td>$item[k2]</td><td>$item[kTypes][kType1][desc]</td><td>$item[kTypes][kType2][desc]</td>";
}
echo '</table>';
which works fine for the first both columns, but not the ktype ones. There the:
echo is "Array[kType2][desc]"
So I tried a nested loop, but this didn't work, too.
can anyone help me on the right track?
To interpolate multidimensional array accesses in a string, you have to use the "complex" format with curly braces.
echo "<tr><td>$item[k1]</td><td>$item[k2]</td><td>{$item['kTypes']['kType1']['desc']}</td><td>{$item['kTypes']['kType2']['desc']}</td>";
Try this foreach for your specific piece:
echo "<tr>";
foreach ($items as $field => $value) {
if($field =='ktype'} {
foreach($items['ktype'] as $ktype) {
foreach($ktype as $k) {
echo "<td>{$k}</td>";
}
}
} else {
echo "<td>{$value}</td>";
}
}
echo "</tr>";
However, I would do a recursive piece so it can go as deep into the array as possible.

PHP Array output from result array values

Below is my result array:
Array
(
[0] => Array
(
[id] => 3
[name] => test
)
[1] => Array
(
[id] => 4
[name] => Balikavadhu
)
)
From above array, I want to generate a new array as below:
array(3,4) // where 3 and 4 are id values of respective array
Any help or quick answer will be appreciated.
Thanks in advance !
Yet another option:
$newArray = [];
foreach ($arrayResults as $result) {
$newArray[] = $result['id'];
}
Put your output array into an array called $arr. Then do this :
$newArr = array();
$id = 0;
foreach ($arr as $val)
{
$newArr[$i] = $val['id'];
$id++;
}
You could do something like
$newArray = [];
foreach ($arrayResults as $result) {
array_push($newArray, $result['id']);
}

Getting values from associative array

I have the following main array called $m
Array
(
[0] => Array
(
[home] => Home
)
[1] => Array
(
[contact_us] => Contact Us
)
[2] => Array
(
[about_us] => About Us
)
[3] => Array
(
[feedback_form] => Feedback Form
)
[4] => Array
(
[enquiry_form] => Products
)
[5] => Array
(
[gallery] => Gallery
)
)
I have the values eg home, contact_us in a array stored $options , I need to get the values from the main array called $m using the $options array
eg. If the $options array has value home, i need to get the value Home from the main array ($m)
my code looks as follows
$c = 0;
foreach($options as $o){
echo $m[$c][$o];
++$c;
}
I somehow just can't receive the values from the main array?
I'd first transform $m to a simpler array with only one level:
$new_m = array();
foreach ($m as $item) {
foreach ($item as $key => $value) {
$new_m[$key] = $value;
}
}
Then you can use:
foreach ($options as $o) {
echo $new_m[$o];
}
Try this:
foreach($options as $o){
foreach($m as $check){
if(isset($check[$o])) echo $check[$o];
}
}
Although It would be better TO have the array filled with the only the pages and not a multidimensional array
Assuming keys in the sub arrays are unique you can
merge all sub arrays into a single array using call_user_func_array on array_merge
swap keys and values of your option array
Use array_intersect_key to retrieve an array with all the values.
Example like so:
$options = array('about_us', 'enquiry_form');
$values = array_intersect_key(
call_user_func_array('array_merge', $m), // Merge all subarrays
array_flip($options) // Make values in options keys
);
print_r($values);
which results in:
Array
(
[about_us] => About Us
[enquiry_form] => Products
)
How's this?
foreach( $options as $option )
{
foreach( $m as $m_key => $m_value )
{
if( $option == $m_key )
{
echo 'Name for ' . $options . ' is ' . $m_value;
break;
}
}
}
Try using a recursive array_walk function, for example
$a = array(
array('ooo'=>'yeah'),
array('bbb'=>'man')
);
function get_array_values($item, $key){
if(!is_numeric($key)){
echo "$item\n";
}
}
array_walk_recursive($a,'get_array_values');
Are you sure that the options array is in the same order of $m? Maybe you your
echo $m[$c][$o];
is resolving into a $m[0]['gallery'] which is obviously empty.
you can try different solutions, to me, a nice one (maybe not so efficient) should be like this:
for($c=0, $limit=count($c); $c < $limit; $c++)
if (array_search(key($m[$c]), $options))
echo current($m[$c]);
If you would like to use your approach have to flatten your array with something like this:
foreach ($m as $o)
$flattenedArray[key($o)]=current($o);
foreach ($options as $o)
echo $flattenedArray($o);
Doing this, though, eliminates duplicate voices of your original array if there are such duplicates.
$trails1 = array();
foreach ($trails as $item) {
foreach ($item as $key => $value) {
$trails1[].= $value;
}
}
echo '<pre>';print_r($trails1);
exit;

Categories