how to filter multidimensional array. php - php

I have some confusing issue here. please take a look and help if you don't mind.
let's say i have this multidimensional array, called $array.
[1] => Array
(
[3] => 2
[2] => 5
[4] => 4
)
[3] => Array
(
[1] => 2
)
[2] => Array
(
[1] => 5
)
that array is representing a path between two node. I try to implmenting dijkstra algorhitm here. when it's
$array[1][2] = 5
that's mean the distance between node 1 to node 2 is 5 and so on.
what Im asking is, how can I detect that array $array[1][4] = 4 doesn't have a reverse path such $array[4][1] = 4 like the example above.
thank you in advance.

Follow this:
$temp = array();
$array = array('1' => Array
(
'3' => 2,
'2' => 5,
'4' => 4
),
'3' => Array
(
'1' => 2
),
'2' => Array
(
'1' => 5
));
foreach ($array as $key => $value)
{
foreach ($value as $k => $v)
{
if($array[$key][$k] == isset($array[$k][$key]))
{
echo $key . 'to' . $k . 'reverse path available';
echo "<br>";
}
}
}

Like this.Loop foreach inside another foreach and check based on keys.
$array = array('1'=>array('3'=>2),'3'=>array('1'=>2));//assumed reversed array
//print_r($array);
foreach($array as $key=>$value){
foreach($value as $k=>$v){
if($array[$key][$k] == $array[$k][$key]){
echo "Reverse at:array[".$key."][".$k."]".PHP_EOL;
continue;
}
}
}
Output:
Reverse at:array[1][3]
Reverse at:array[3][1]

for that array you have to add nested for loop..
for($i=0;$i<count($your_array);$i++)
{
for($j=0;$j<count($your_array[$i]);$j++)
{
if(isset($your_array[$i][$j]) && isset($your_array[$j][$i]) && $your_array[$i][$j]==$your_array[$j][$i])
{
echo "same distance";
}
else
{
echo "different distance or path not available";
}
}
}

Related

Replacing values in the array nvp

I have been trying to replace the values in the array
I'll name this array as $currencies when i print this it looks like.
Array
(
[0] => Array
(
[currencylabel] => USA, Dollars
[currencycode] => USD
[currencysymbol] => $
[curid] => 1
[curname] => curname1
[check_value] =>
[curvalue] => 0
[conversionrate] => 1
[is_basecurrency] => 1
)
[1] => Array
(
[currencylabel] => India, Rupees
[currencycode] => INR
[currencysymbol] => ₨
[curid] => 2
[curname] => curname2
[check_value] =>
[curvalue] => 0
[conversionrate] => 50
[is_basecurrency] =>
)
[2] => Array
(
[currencylabel] => Zimbabwe Dollars
[currencycode] => ZWD
[currencysymbol] => Z$
[curid] => 3
[curname] => curname3
[check_value] =>
[curvalue] => 0
[conversionrate] => 22
[is_basecurrency] =>
)
)
Here I am having a $conversionRate to which i need to divide the values present in the array $currencies [0] -> Array -> [conversionrate] and replace in the same place in array.
and the same operation for [1] -> Array -> [conversionrate] and so on..
for which my current approach is as follows
$conversionRate = 50;
foreach ($currencies as $key => $val) {
$key['conversionrate'] = $key['conversionrate'] / $conversionRate;
if($key['conversionrate'] == 1) {
$key['is_basecurrency'] = 1;
} else {
$key['is_basecurrency'] = '';
}
}
print_r($key);
die;
Currently this is not working kindly help
Your loop is all wrong, there is no $key['conversionrate'], it's $val['conversionrate']. In fact there doesn't seems to be a reason for the $key variable, you can just loop through the array with
foreach ($currencies as &$val)
Also, you probably want to print_r($currencies), not $key
Do not compare floating point numbers with == to 1, it might not work due to rounding errors.
You mixed up key and value and you need to use &$val to be able to change the array.
$conversionRate = 4;
foreach ($currencies as $key => &$val) {
if($val['conversionrate'] == $conversionRate) {
$val['is_basecurrency'] = 1;
} else {
$val['is_basecurrency'] = '';
}
$val['conversionrate'] = $val['conversionrate'] / $conversionRate;
}
unset($val);
print_r($currencies);
die;
$key is an index identofoer of an array and $val contain array values
so use like this
$conversionRate = 4;
foreach ($currencies as $key => $val) {
$val['conversionrate'] = $val['conversionrate'] / $conversionRate;
if($val['conversionrate'] == 1) {
$val['is_basecurrency'] = 1;
} else {
$val['is_basecurrency'] = '';
}
}
print_r($val);
die;

How to group the result of array in two categories in PHP?

I have data here:
Array
(
[1] => Array
(
[SiteID] => 1
[OwnerAID] => 1
)
[3] => Array
(
[SiteID] => 3
[OwnerAID] => 1
)
[6] => Array
(
[SiteID] => 6
[OwnerAID] => 2
)
)
Now, I need to group the OwnerAID into two categories: the first one is OwnerAID owning only one SiteID and the second one is OwnerAID owning more than 1 SiteID.
I've tried to make a program and do some research, but the output of my code is wrong.
Please see my code:
public function groupIndividualAndAggregateSites()
{
$arrays = array();
foreach($this->combined as $key => $key_value)
{
$SiteID = "";
if ($SiteID == "") {
$SiteID=array($key_value['SiteID']); }
else {
$SiteID = array_merge((array)$SiteID, (array)$key_value['SiteID']);
$SiteID = array_unique($SiteID);
}
} if ($SiteID != "") {
$arrays = array('AID'=>$key_value['AID'], 'Sites' => $SiteID);
}
print_r($arrays);
}
The result should be shown like this:
Array(
[1] => Array
( [Sites] => Array ([0] => 1, [1] => 3)))
Array(
[2] => Array
( [Sites] => Array ([0] => [6]))
What you should go for is array:
$owners = array(
owner_1 => SiteID1, // int Only one site
owner_2 => array (SiteID2,SiteID3), // array Multiple sites
);
and later use the array $owners like:
echo (is_array($owners[$owner_1]) ? 'Has multiple sites' : 'has one site';
Thats the basic idea of small memory footprint.
Example, not tested.
public function groupIndividualAndAggregateSites() {
$owners = array();
foreach($this->combined as $key => $value) {
$owner_id = $value['OwnerAID'];
$site_id = $value['SiteID'];
if(array_key_exists($owner_id,$owners)) {
// He has one or more sites already?
if(is_array($owners[$owner_id]){
array_push($owners[$owner_id],$site_id);
} else {
// User already has one site. Lets make an array instead and add old and new siteID
$old_site_id = $owners[$owner_id];
$owners[$owner_id] = array($old_site_id,$owner_id);
}
} else {
$owners[$owner_id] = $site_id;
}
return $owners;
}
All you need to do is loop over your initial array, appending each OwnerAID to the relevant output subarray as determined by the SiteID:
$output = array(1=>array(), 2=>array());
foreach ($original as $v) $output[$v['SiteID'] == 1 ? 1 : 2][] = $v['OwnerAID'];
Here I am using the following features:
array() initialisation function;
foreach control structure;
ternary operator;
$array[$key] addressing;
$array[] pushing.

Find value and key in multidimensional array

I have the following array:
Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
I need to find if [position] => 22 exists in my array and retain the array path for further reference. Thank you.
Example of code for the solution "Ancide" provide.
$found = false;
foreach ($array as $array_item) {
if (isset($array_item['position'] && $array_item['position'] == "22")) {
$found = true;
break;
}
}
You can try this code:
$array = array
(
array (
"word" => 1,
"question" => php,
"position" => 11
),
array (
"word" => sql,
"question" => 1,
"position" => 22
)
);
foreach($array as $item)
{
foreach($item as $key=>$value)
{
if($key=="position" && $value=="22")
{
echo "found";
}
}
}
First check if they key exists using isset, then if the key exists, check that the value is equal to your compare value.
Edit: I missed that there were two arrays. To solve this, iterate through each array and do the check in each cycle. If the check is positive you know which array it is by looking at the current index.
I think there is no other solution than to loop through the array an check whether there is a key "position" and value "22"
This will solve your problem:
<?php
foreach ($array as $k => $v) {
if(isset($v['position']) && $v['position'] == 22) {
$key = $k;
}
}
echo $key;
//$array[$key]['position'] = 22
?>
Try this:
function exists($array,$fkey,$fval)
{
foreach($array as $items)
{
foreach($items as $key => $val)
if($key == $fkey and $val == $fval)return true;
}
return false;
}
Example:
if(exists($your_array,"position",22))echo("found");
function findPath($array, $value) {
foreach($array as $key => $subArray) if(subArray['position'] === $value) return $key;
return false; // or whatever if not found
}
echo findPath($x, 22); // returns 1
$x= Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
Try with this function:
function findKey($array, $mykey) {
if(array_key_exists($mykey, $array))
return true;
foreach($array as $key => $value) {
if(is_array($value))
return findKey($value, $mykey);
}
return false;
}
if(findKey($search_array, 'theKey')) {
echo "The element is in the array";
} else {
echo "Not in array";
}

How to get particular array value in php?

I have the following $qtips_messages array,
Array
(
[0] => Array
(
[id] => 1
[tips_title] => email_tips
[tips_message] => ex:xxxxx#xyz.com
[tips_key] => key_email
)
[1] => Array
(
[id] => 2
[tips_title] => website_tips
[tips_message] => ex:http://www.yahoo.co.in
[tips_key] => key_website
)
[2] => Array
(
[id] => 3
[tips_title] => zipcode_tips
[tips_message] => ex:60612
[tips_key] => key_zipcode
)
[3] => Array
(
[id] => 4
[tips_title] => phone_tips
[tips_message] => ex:1234567890
[tips_key] => key_phone
)
)
For example, I want to get the tips message for the tip_title 'email_tips'
I have tried with following code,
foreach($qtips_messages as $qtipsArray){
foreach($qtipsArray as $qkey=>$qvalue){
if($qtipsArray['tips_title'] == 'email_tips'){
$emailtipsMessage = $qtipsArray['tips_message'];
}
}
}
When i ran the above code i did not get any value.
What is wrong with this code?
You only need one loop:
$message = null;
foreach ($array as $tips) {
if ($tips['tips_title'] == 'email_tips') {
$message = $tips['tips_message'];
break;
}
}
I'd probably go for something like this though:
$message = current(array_filter($array, function ($tip) { return $tip['tips_title'] == 'email_tips'; }));
echo $message['tips_message'];
$array = array();
foreach($result AS $k =>$val)
$array[$val['tips_key']] = $val['tips_message'];
return $array;
Now the array $array have all the values for q-tips based on their keys...
Hope this will helps you...
try this way.
$array = array();
foreach($qtips_messages AS $k =>$val):
if($val['tips_title']=='email_tips')
{
$array[$val['tips_key']] = $val['tips_message'];
print_r($array);
break;
}
endforeach;

changing keys of a multidimensional array

I have a multidimensional array as shown below. How do I change the keys that start with "id of"?
Array
(
[0] => Array
(
[id of ten] => 1871
[name] => bob
)
[1] => Array
(
[id of nine hundred thousand] => 12581
[name] => barney
)
)
Normally, you'd do something like:
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['old'];
unset($array[$k]['old']);
}
In my case, the key changes dynamically (there are thousands of keys in my multidimensional array and they are random but they will always start w/ "id of...")
thx!
I'm wondering if this is what you are looking for:
<?php
$array = array(
array(
"id of one" => 434,
"name" => "bob"
),
array(
"id of two" => 9323,
"name" => "ted"
)
);
$c_array = count($array);
for ($i = 0; $i < $c_array; $i++)
{
foreach ($array[$i] as $key => $value)
{
if (substr($key, 0, 5) == 'id of') {
$array[$i][substr($key, 6)] = $value;
unset($array[$i][$key]);
}
}
}
print_r($array);
?>
NOTE: Includes use of substr() instead of strpos(). See Gumbo's comment below.
https://ideone.com/xBV5L
This outputs:
Array
(
[0] => Array
(
[name] => bob
[one] => 434
)
[1] => Array
(
[name] => ted
[two] => 9323
)
)
This solution is very clean. Array_shift, does two things at once: returns first element (which has the id), and deletes it from the array, so you can directly assign it to the $new_array at 'id'
$new_arr=array();
foreach ( $array as $arr)
{
$new_arr[array_shift($arr)] = $arr;
}
If the 'id of' key is always the first element of the array, you can use the following:
foreach ($input as &$value)
{
$value['key'] = reset($value);
$key = key($value);
unset($value[$key]);
}
Otherwise, the following worked for me:
foreach ($input as &$value)
{
foreach ($value as $key=>$el) {
if (substr($key, 0, 5) == 'id of') {
$value['key'] = $el;
unset($value[$key]);
}
}
}
In both cases you can change $value['key'] to whatever you want the new key to be.

Categories