How can I sum an especial index in array for example I wanna sum -age(it's an index) in this array:
$users = array(
"user1" => array("name" => "Loghman Avand", "age" => 26),
"user2" => array("name" => "Sara Alavi", "age" => 34),
"user3"=> array("name" => "Hossein Ahmadi", "age" => 3)
);
Use array_column() and array_sum():
$ages = array_column($users, 'age');
echo 'Sum is: ', array_sum($ages);
This is ignoring the fact your keys in the outer array are the same.
First thing is your above array is invalid. Because same array key ('users') is used mode than one time.
Check this below code
$users = array("user1" => array("name" => "Loghman Avand", "age" => 26), "user2" => array("name" => "Sara Alavi", "age" => 34), "user3" => array("name" => "Hossein Ahmadi", "age" => 3));
$age_sum = 0;
foreach($users as $user){
$age_sum += $user['age'];
}
echo $age_sum;
Related
How is it possible to pick a random value with PHP from an Array?
Example:
$trees = [
"appletree" => [
"id" => "12378",
"age" => [15],
"height" => [6]
],
"bananatree" => [
"id" => "344343453",
"age" => [16],
"height" => [30]
],
"peachtree" => [
"id" => "34534543",
"age" => [35],
"height" => [4]
];
How would I access one of the id's randomly?
I tried using
$tree_id = array_rand($trees['id']);
echo $tree_id;
echo "\r\n";
but I'm slowly hitting a wall of understanding.
array_rand() returns a random array key. So give it the $trees array to get a tree name, then use that to index the array and access its id property.
$random_tree = array_rand($trees);
echo $trees[$random_tree]['id'];
maybe this function I created can help:
<?php
$trees = [
"appletree" => [
"id" => "123",
"age" => [15],
"height" => [6]
],
"bananatree" => [
"id" => "456",
"age" => [16],
"height" => [30]
],
"peachtree" => [
"id" => "789",
"age" => [35],
"height" => [4]
] // <- you were missing this bracket
];
function pickRand($array){
// Create Temp array
$temparray = [];
// Iterate through all ID's and put them into out temp array
foreach($array as $a) $temparray[] = $a['id'];
// Get a random number out of the number of ID's we have
$rand = rand(0, count($temparray) - 1);
// Return Result
return $temparray[$rand];
}
// Use Function
echo pickRand($trees);
Live Demo: http://sandbox.onlinephpfunctions.com/code/e71dc6b07c3ec93051c69adc66b28aafe555a104
I have created an Array but I am not getting the correct output, I am just wondering where I made error in code below
The Out put should display the name as below
John
James
Jonny
Jeni
<?php
$multiArray = Array(
Array("id" => 1, "name" => "John"),
Array("id" => 2, "name" => "James"),
Array("id" => 3, "name" => "Jonny"),
Array("id" => 4, "name" => "Jeni"));
$tmp = Array();
foreach($multArray as &$ma)
$tmp[] = &$ma[name];
array_multisort($tmp, $multiArray);
foreach($multiArray as &ma)
echo $ma["name"]."<br/>";
?>
What are you trying to achieve here? Are you trying to only print the content of the array?
Just do it like this is enough
<?php
$multiArray = Array(
Array("id" => 1, "name" => "John"),
Array("id" => 2, "name" => "James"),
Array("id" => 3, "name" => "Jonny"),
Array("id" => 4, "name" => "Jeni")
);
foreach($multiArray as $ma)
{
echo $ma['name'] . "<br>";
}
?>
Also I noticed that in your codes, there is a lot of typo there.
This is your codes after I fixed all the typos:
<?php
$multiArray = Array(
Array("id" => 1, "name" => "John"),
Array("id" => 2, "name" => "James"),
Array("id" => 3, "name" => "Jonny"),
Array("id" => 4, "name" => "Jeni")
);
$tmp = Array();
foreach($multiArray as $ma)
$tmp[] = $ma['name'];
array_multisort($tmp, $multiArray);
foreach($multiArray as $ma)
echo $ma["name"]."<br/>";
?>
Output:
James
Jeni
John
Jonny
Yes the output is different from what you want. this is because you sort the array using array_multisort. read: http://php.net/manual/en/function.array-multisort.php
I've that proceed this array in PHP
array(
"id" => 1,
"name" => "Carlos"
"other" => array("key" => "Hello")
),
array(
"id" => 3,
"name" => "Carlos"
"other" => array("key" => "Hello")
),
array(
"id" => 2,
"name" => "Carlos"
"other" => array("key" => "Hello")
)
and I need to order by "id". I've try it using usort and many multidimensional solutions but doesn't work for me.
I used that:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
But doesn't work because my array has many dimentions.
$departamento = $this->Departamentos->get($id, [
'contain' => [
'Asignaturas.Mallas',
'Asignaturas.Secciones.Perfiles',
'Asignaturas.Secciones.Mallas.Carreras',
'Unidades'
]
]);
That is my query in Cakephp. I need to order by Secciones.id
I used Hash::sort
http://book.cakephp.org/3.0/en/core-libraries/hash.html
And works fine for me ;)
I have 2 arrays, $array0 and $array1. Let's pre-fill them:
$user01 = array("no" => 1, "name" => "john");
$user02 = array("no" => 2, "name" => "lewis");
$user03 = array("no" => 3, "name" => "dan");
$array0 = array($user01, $user02, $user03, $user04);
$user11 = array("id" => 1, "name" => "john", "attr" => "foo");
$user12 = array("id" => 7, "name" => "mark", "attr" => "bar");
$array1 = array($user11, $user12);
I want to get all users from $array0 who are not in $array1, so I use array_udiff:
$diff = array_udiff($array0, $array1, function ($userA, $userB) {
return $userA['no'] == $userB['id'];
});
However, inside the anonymous compare function, if I do a var_dump of $userA and $userB, they both seem to belong to $array0, while the behavior I was expecting is for $userA to belong to $array0 and $userB to $array1.
I.e., the expected answer is [[2, "lewis"], [3, "dan"]], but I get a 'not found index': "Undefined index id" in the line of the comparison function.
Am I missing something on array_udiff behavior?
I'm pretty sure PHP expects the arguments to the comparison function to be interchangeable, you either need to change the array indexes to be common, or implement logic in the comparison function to deal with this.
That's not how a comparison function works.
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
So:
$user01 = array("id" => 1, "name" => "john"); // "no" changed to "id"
$user02 = array("id" => 2, "name" => "lewis");
$user03 = array("id" => 3, "name" => "dan");
$array0 = array($user01, $user02, $user03); // non-existant $user04 removed
$user11 = array("id" => 1, "name" => "john", "attr" => "foo");
$user12 = array("id" => 7, "name" => "mark", "attr" => "bar");
$array1 = array($user11, $user12);
$diff = array_udiff($array0, $array1, function ($userA, $userB) {
if( $userA['id'] == $userB['id'] ) { return 0; } // compare function re-jiggered
else { return $userA['id'] - $userB['id']; }
});
print_r($diff);
Yields:
Array
(
[1] => Array
(
[id] => 2
[name] => lewis
)
[2] => Array
(
[id] => 3
[name] => dan
)
)
I have this array:
array(
"tour_0" => 1446,
"tour_1" => 1471,
"date-from-1471" => "2014-08-07",
"date-to-1471" => "2014-08-15",
"tour_2" => 30,
"date-from-30" => 2014-08-01,
"date-to-30" => 2014-08-05,
"tour_3" => 10
)
Now, i need it to be sorted to this:
array(
"0" => array("ID" => 1446),
"1" => array("ID" => 1471, "from" => "2014-08-07", "to" => "2014-08-15"),
"2" => array("ID" => 30, "from" => "2014-08-07", "to" => "2014-08-15"),
"3" => array("ID" => 10),
)
How can i accomplish this thing?
I've tried all sorts of things but i can't seem to figure this one out...
Thank's and sorry about the title but i just don't know how to describe it.
How about this?
$ret = [];
foreach($inputArray as $key => $value) {
if (preg_match('/^tour_([0-9]+)/', $key)) {
$ret[$value] = ["ID" => $value];
}
if (preg_match('/date-from-([0-9]+)/', $key, $matches)) {
$ret[$matches[1]]["from"] = $value;
}
if (preg_match('/date-to-([0-9]+)/', $key, $matches)) {
$ret[$matches[1]]["to"] = $value;
}
}
print_r($ret);
/*
Array
(
"1446" => Array ("ID" => 1446),
"1471" => Array ("ID" => 1471, "from" => "2014-08-07", "to" => "2014-08-15"),
"30" => Array ("ID" => 30, "from" => "2014-08-01", "to" => "2014-08-05"),
"10" => Array ("ID" => 10)
)*/
Close enough? (it is quite trival change the keys of the array, considering they are in order (0, 1, 2, 3, ...), if they are not, maybe you can save the order also (in another item of the subarray) and recompose again once this array is formed)