Manipulating multidimensional array in PHP? - php

array(2) {
[0]=>
object(stdClass)#144 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(5) "name1"
}
[1]=>
object(stdClass)#145 (2) {
["id"]=>
string(1) "4"
["name"]=>
string(5) "name2"
}
}
I want to add key and value (for example [distance] = 100;) to the objects in the array. After this I want to sort on the distance values. How can I achieve this?

To get structure such as yours you can do:
$arr = array();
$arr[0]->id = "2";
$arr[0]->name = "name1";
$arr[1]->id = "4";
$arr[1]->name = "name2";
To add "distance" you can do:
$arr[0]->distance = 100;
$arr[1]->distance = 200;
To sort you can use decorate/sort/undecorate pattern:
$arr = array_map(create_function('$o', 'return array($o->distance, $o);'), $arr); // transform array of objects into array of arrays consisted of sort key and object
sort($arr); // sort array of arrays
$arr = array_map('end', $arr); // take only last element from each array
Or you can use usort() with custom comparison function like this:
function compareDistanceFields($a, $b) {
return $a->distance - $b->distance;
}
usort($arr, "compareDistanceFields");

$my_array[0]->distance = 100;
$my_array[0]->distance = 101;
usort($my_array, "cmp");
function cmp($a, $b)
{
if ($a->distance == $b->distance)
return 0;
return ($a->distance > $b->distance) ? 1: -1;
}

What you have here is an array of hashes; that is, each element of your array is a hash (a structure containing elements, each of which is identified by a key).
In order to add a key and value, you just assign it, like this:
$array[0]["distance"]=100;
$array[1]["distance"]=300;
#and so on
PHP hashes and arrays in general are documented here.
Now, in order to sort your array (each of whose elements is a hash), you need to use the "uasort" function, which allows you to define a comparison function; in this comparison function you define the behavior you want, which is sorting on the value of the distance key.
Something like this:
// Comparison function, this compares the value of the "distance" key
// for each of the two elements being compared.
function cmp($a, $b) {
if ($a["distance"] == $b["distance"]) {
return 0;
}
return ($a["distance"] < $b["distance"]) ? -1 : 1;
}
Once this is defined, you call uasort like this:
uasort($array, 'cmp');
Find more documentation on uasort here.

Related

How to change php array position with condition in Php

I am working with PHP,I have array and i want to change position of array, i want to display matching value in first position,For example i have following array
$cars=('Toyota','Volvo','BMW');
And i have variable $car="BMW" And i want to match this variable with array and if match then this array value should be at first in array
so expected result is (matching record at first position)
$cars=('BMW','Volvo','Toyota');
How can i do this ?
You can use array_search and array_replace for this purpose. try below mentioned code
$cars=array(0 =>'Toyota',1 =>'Volvo',2 =>'BMW');
$car="BMW";
$resultIndex = array_search($car, $cars); //get index
if($resultIndex)
{
$replacement = array(0 =>$car,array_search($car, $cars)=>$cars[0]); //swap with 0 index
$cars = array_replace($cars, $replacement); //replace
}
print_r($cars);
This can be solved in one line with array_merge and array_unique array functions.
$cars=['Toyota','Volvo','BMW'];
$car="BMW";
$cars2 = array_unique(array_merge([$car],$cars));
//$cars2: array(3) { [0]=> string(3) "BMW" [1]=> string(6) "Toyota" [2]=> string(5) "Volvo" }
$car is always at the beginning of the new array due to array_merge. If $car already exists in the $cars array, array_unique will remove it. If $car is not present in the $cars array, it is added at the beginning. If this behavior is not desired, you can use in_array to test whether $car is also contained in the $cars array.
The simplest is to "sort" by "Value = BMW", "Value != BMW".
The function that sorts and resets the keys (i.e. starts the resulting array from 0, which you want) is usort (https://www.php.net/manual/en/function.usort.php)
So your comparison function will be If ($a == "BMW") return 1, elseif ($b == "BMW") return -1, else return 0; (Paraphrased, don't expect that to work exactly - need to leave a bit for you to do!)

A list of random float number from 0 to 1 using php?

I want to create a function to print a list of 50 random floats from 0 to 1.
The function to print one random float is simply :
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}
But how do I get a list of 50 numbers in descending order?
I want to use usort() function, but I am not sure how to use it with a list of 50 random floats.
Generate a array of floats, sort with sort(), then reverse the array to give descending order.
So, using your function:
<?php
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}
$arr = [];
for ($i=0;$i<50;$i++) {
$arr[] = random_from_0_to_1();
}
sort($arr); // sorts ascending
$arr = array_reverse($arr);
var_dump($arr);
Output:
array(50) {
[0]=>
float(0.9991139778863238)
[1]=>
float(0.9733540797482031)
[2]=>
float(0.9620095835821748)
[3]=>
float(0.9390542404442347)
[4]=>
float(0.9368096925023989)
[5]=>
float(0.9321818514411253)
[6]=>
float(0.9321091510039331)
...
Demo: https://3v4l.org/NJvGu
[Edit]
Since you've specifically asked for a version with usort(), try this, which substitutes usort() for sort() and array_reverse():
<?php
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}
$arr = [];
for ($i=0;$i<50;$i++) {
$arr[] = random_from_0_to_1();
}
usort($arr, function($a,$b){return $b<=>$a;}); // Note parameters reversed in spaceship comparison
var_dump($arr);
Demo: https://3v4l.org/qn7Ka

Why "foreach" don't echo?

Learn php
<?php
$a = 3;
if ($a>1){
$arr = array (1,2,3);
}
foreach ($arr as $b) {
echo $b[0];
echo $b[1];
echo $b[2];
}
var_dump($arr);
?>
I don't know why it can not echo in foreach?
But var_dump($arr) still run with result:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
But when I wrote: $arr[] it can run.
<?php
$a = 3;
if ($a>1){
$arr[]= array (1,2,3);
}
foreach ($arr as $b) {
echo $b[0];
echo $b[1];
echo $b[2];
}
var_dump($arr);
?>
Result:
123
array(1) { [0]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } }
Both of them are same result with var_dump. So what different between $arr and $arr[] ?
These two lines:
$arr = array (1,2,3);
and
$arr[]= array (1,2,3);
are not equivalent. Look more closely at the two var_dump outputs, and you'll see the difference.
In the former, you're creating a one dimensional array - when you try to loop over it, you'll get an iteration with $b set to each of the three values (1, 2 and 3) in turn. Each time, $b is an integer. Any "index" of it will return null, since you can't deference scalar values (other than strings). This is defined in the manual here:
Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.
And when you echo null, nothing happens. It's the equivalent of an empty string, and so no output is produced.
In the second case, you're creating a two dimensional array. Writing
$arr[]= array (1,2,3);
when $arr is empty is the same as writing
$arr = array(array (1,2,3));
This time, when you loop over it, you get a single iteration, with $b set to the inner array. Now, echo-ing $b[0], $b[1] and $b[2] refers to the integers in the array, so you get your expected output of
123
Use this code instead of you written above:
<?php
$a = 3;
if ($a>1){
$arr = array (1,2,3);
}
foreach ($arr as $b) {
echo $b;
echo '<br>';
}
var_dump($arr);
?>

comparing two array php array_diff

I got an empty array when I compare two arrays that have the different key but the same value. Example: id has the same value like yy
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
What I want is :
$a = array('id'=>12,'id'=>2);
You can use array_merge_recursive() - (PHP 4 >= 4.0.1, PHP 5, PHP 7)
From PHP Manual:
array_merge_recursive — Merge two or more arrays recursively
<?php
$a = array('id'=>2,'name'=>'D','yy'=>12);
$b = array('id'=>12,'name'=>'D','yy'=>12);
$result = array_merge_recursive($a, $b);
$newArr = $result['id']; // get ID index. you can also get other indexes.
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[0] => 2
[1] => 12
)
Note that: you can not use same index name (ID) for this array array('id'=>12,'id'=>2);
As #Ghost mentioned, an associative array should not have the same keys.
I suggest to achieve the "expected result" in "nested arrays" manner using array_diff_assoc function(computes the difference of arrays with additional index check):
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
echo "<pre>";
$result_nested_arr = [array_diff_assoc($o, $n), array_diff_assoc($n, $o)];
var_dump($result_nested_arr);
// the output:
array(2) {
[0]=>
array(1) {
["id"]=>
int(2)
}
[1]=>
array(1) {
["id"]=>
int(12)
}
}
http://php.net/manual/en/function.array-diff-assoc.php

php array comparison index by index

If there are two array variable which contains exact same digits(no duplicate) but shuffled in position.
Input arrays
arr1={1,4,6,7,8};
arr2={1,7,7,6,8};
Result array
arr2={true,false,false,false,true};
Is there a function in php to get result as above or should it be done using loop(which I can do) only.
This is a nice application for array_map() and an anonymous callback (OK, I must admit that I like those closures ;-)
$a1 = array(1,4,6,7,8);
$a2 = array(1,7,7,6,8);
$r = array_map(function($a1, $a2) {
return $a1 === $a2;
}, $a1, $a2);
var_dump($r);
/*
array(5) {
[0]=>
bool(true)
[1]=>
bool(false)
[2]=>
bool(false)
[3]=>
bool(false)
[4]=>
bool(true)
}
*/
And yes, you have to loop over the array some way or the other.
You could use array_map:
<?php
$arr1= array (1,4,6,7,8) ;
$arr2= array (1,7,7,6,8) ;
function cmp ($a, $b) {
return $a == $b ;
}
print_r (array_map ("cmp", $arr1, $arr2)) ;
?>
The output is:
Array
(
[0] => 1
[1] =>
[2] =>
[3] =>
[4] => 1
)
Any way this job is done must be using looping the elements. There is no way to avoid looping.
No metter how you try to attack the problem and even if there is a php function that do such thing, it uses a loop.
You could use this http://php.net/manual/en/function.array-diff.php, but it will not return an array of booleans. It will return what data in array 1 is not in array 2. If this doesn't work for you, you will have to loop through them.
there's array_diff() which will return an empty array in case they are both equal.
For your spesific request, you'll have to iterate through the arrays and compare each item.

Categories