How to sort array using object element in php? - php

I have following php array object:
"requests": [
{
"id": 111,
"time: 123123123,
"data": "testc"
},
{
"id": 200 ,
"time: 433123123,
"data": "testb"
},
{
"id": 300 ,
"time: 33123123,
"data": "testb"
}
]
I want to sort it by requests->time only. How to do it?
I don't want sort by id. All data should be sort as per time ASC.

supposing you have that array in a $requests variable, the following should work
<?php
function cmp($a, $b)
{
return strcmp($a["time"],$b["time"]);
}
usort($requests, "cmp");
//print for test
while (list($key, $value) = each($requests)) {
echo "\$requests[$key]: " . $value["time"] . "\n";
}
?>

You have to use your own sort method with usort()
Solution :
<?php
function sortByTimeASC($a, $b)
{
if ($a->time == $b->time) {
return 0;
}
return ($a->time < $b->time) ? -1 : 1;
}
$a = json_decode('[{"id": 111,"time": 123123123,"data": "testc"},{ "id":200 ,"time":433123123,"data":"testb"},{"id":300,"time":33123123,"data":"testb"}]');
usort($a, "sortByTimeASC");
print_r($a);
?>
Live example

Related

Variable for the dimensions of a multivariable array

I am trying to generalize some code in a function so that I can read different JSON formatted input and determine system information from each. For brevity, I am not including all of the code. In the actual code, I am retrieving the value of $length from a database.
Here is an example:
function readHostname($json, $length) {
$content = json_decode($json, true);
$hostname = $content[$length];
}
$json = file_get_contents($url1, false, $context);
$length = "[0]['cluster']['nodes'][0][hostName]";
echo readHostname($json, $length);
$json = file_get_contents($url2, false, $context);
$length = "[0]['components']['serviceName']";
echo readHostname($json, $length);
For reference url1 would return JSON such as:
[
{
"cluster": {
"nodes": [
{ "name": "cluster1",
"hostName": "alpha"
},
{ "name": "cluster2",
"hostName": "beta"
}
]
}
},
{
"cluster": {
"nodes": [
{ "name": "prod_cluster1",
"hostName": "oscar"
},
{
"name": "prod_cluster2",
"hostName": "delta"
}
]
}
}
]
and url2 would return json:
[
{
"compenents": {
"serviceName" : "hostname1",
"environment" : "produciton"
}
}
]
You want flexible access to nested array structures. Replace your readHostname function with this:
function readHostname($json, $length) {
$content = json_decode($json, true);
preg_replace_callback('/\[([^]]+)\]+/', function($m) use(&$content) {
$index = $m[1];
$content = $content[preg_match('/[0-9]+/', $index) ? intval($index) : trim($index, "'\"")];
}, $length);
return $content;
}
You can abstract the process and use recursion.
function getHost($payload,$hostName){
$array = is_array($payload) ? $payload : json_decode($payload,true);
if(json_last_error() != JSON_ERROR_NONE){
return;
}
foreach(array_keys($array) as $key){
if($array[$key] == $hostName){
unset($array[$key]);
return $array[key($array)];
}
}
return getHost($array[key($array)],$hostName);
}
echo getHost($payload,"cluster1");
echo getHost($payload,"hostname1");

Create array through function

Is there any way to return an array, something like:
$array = [
"parcela" => "1",
"valor" => "100",
];
Using the function below? I need to return an array with the number of plots and the value:
Function PHP
function calcParcelaJuros($valor_total,$parcelas,$juros=0) {
if($juros==0) {
$string = 'PARCELA - VALOR <br />';
for($i=1;$i<($parcelas+1);$i++) {
$string .= $i.'x (Sem Juros) - R$.number_format($valor_total/$parcelas, 2, ",", ".").' <br />';
}
return $string;
} else {
$string = 'PARCELA - VALOR <br />';
for($i=1;$i<($parcelas+1);$i++) {
$I =$juros/100.00;
$valor_parcela = $valor_total*$I*pow((1+$I),$parcelas)/(pow((1+$I),$parcelas)-1);
$string .= $i.'x (Juros de: '.$juros.'%) - R$ '.number_format($valor_parcela, 2, ",", ".").' <br />';
}
return $string;
}
}
print(calcParcelaJuros(250,4,2));
You only have to save the data on the array, properly formatted as you need, the use the return statement and you are good to go.
You can see, that php's return statement can return values even by reference, as it is explained here; check the second example, it will help you.
But for the sake of giving you a fast example, you can do whatever you need inside the function:
function calcParcelaJuros($valor_total,$parcelas,$juros=0) {
$parcelas = array();
if($juros==0) {
for($i=1;$i<($parcelas+1);$i++) {
...
...
$parcelas[] = ["parcela" => "1", "valor" => "100"]
}
return $parcelas;
} else {
...
...
}
}
You can make any process you require, save the info in the array, then return it.

Sorting a table similar to JSON

I would like to know how to sort my array alphabetically which is like
[
{"people":"Julien SMITH","uid":"598"},
{"people":"John SMITH","uid":"7232"}
]
I tried with
array_multisort($myArray['people'],SORT_ASC,$myArray['uid'])
But of course it doesn't work because people and uid are not really columns of the table...
I can't find something similar to my case..
Thanks for your help
Use usort() function. It will do exactly what you want.
$jsonObj = '[
{"people":"Julien SMITH","uid":"598"},
{"people":"Don SMITH","uid":"7232"},
{"people":"Allan SMITH","uid":"3232"}
]';
$arrObj = json_decode($jsonObj,true);
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($arrObj, build_sorter('people'));
foreach ($arrObj as $item) {
echo $item['people'] . ', ' . $item['uid'] . "n";
}
First you need to convert your json object to array. Then you can apply sorting
$json_obj = '[
{"people":"Julien SMITH","uid":"598"},
{"people":"John SMITH","uid":"7232"}
]';
$myArray = json_decode($json_obj,true);
array_multisort($myArray,SORT_ASC);
echo json_encode($myArray); // op: [{"people":"John SMITH","uid":"7232"},{"people":"Julien SMITH","uid":"598"}]

PHP array check if value in specific key exists

I am using PHP 5.5.12.
I have the following multidimensional array:
[
{
"id": 1,
"type":"elephant",
"title":"Title of elephant"
},
{
"id": 2,
"type":"tiger",
"title":"Title of tiger"
},
{
"id": 3,
"type":"lion",
"title":"Title of lion",
"children":[{
"id": 4,
"type":"cow",
"title":"Title of cow"
},
{
"type":"elephant",
"title":"Title of elephant"
},
{
"type":"buffalo",
"title":"Title of buffalo"
}]
}
]
I am iterating this array using foreach loop.
The array key type must be in elephant, tiger and lion. If not, then the result should return false.
How can I achieve this?
So you want to check if your $myArray contains a value or not:
// first get all types as an array
$type = array_column($myArray, "type");
// specify allowed types values
$allowed_types = ["lion", "elephant", "tiger"];
$count = count($type);
$illegal = false;
// for loop is better
for($i = 0; $i < $count; $i++)
{
// if current type value is not an element of allowed types
// array, then both set the $illegal flag as true and break the
// loop
if(!in_array($type[$i], $allowed_types)
$illegal = true;
break;
}
Since you're using PHP5.5.12, you can make use of array_column.
$arr = json_decode($json, true);
//Walk through each element, only paying attention to type
array_walk( array_column($arr, 'type'), function($element, $k) use(&$arr) {
$arr[$k]['valid_type'] = in_array($element, array('lion', 'tiger', 'elephant'));
});
From here, each element in the array ($arr) will have a new key valid_type with a boolean value - 1 if the type is valid, 0 if it isn't.
https://eval.in/350322
Is this something that you are looking for?
foreach($your_array as $item) {
if (!array_key_exists('type', $item)) {
return FALSE;
}
}
function keyExists($arr, $key) {
$flag = true;
foreach($arr as $v) {
if(!isset($v[$key])) {
$flag = false;
break;
}
}
return $flag;
}
Hope this helps :)

sorting part of a multidimensional array

I have an multi dimensional array:
$array[0] = array ( name => "Bob",
position => "Chair",
email => "bob#foo.bar"
);
$array[1] = array ( name => "Al",
position => "",
email => "al#foo.bar"
);
//etc..
I want to sort it so that those whose position != "" are first, then the rest alphabetically by name... I'm not very familiar w/ sorting multidimensional arrays, could someone help me?
Thanks!
<?php
$array[0] = array ( name => "Bob", position => "Chair", email => "bob#foo.bar");
$array[1] = array ( name => "Al", position => "",email => "al#foo.bar");
print_r($array);
$idxPos = array();
for ($i=0;$i<count($array);$i++)
{
$idxPos[$i] = $array[$i]["position"];
}
arsort($idxPos);
$arrayNew = array();
$sortedKeys = array_keys($idxPos);
for($p=0;$p<count($idxPos);$p++)
{
$arrayNew[] = $array[$sortedKeys[$p]];
}
$array = $arrayNew;
print_r("<br />");
print_r($array);
?>
The usort function is probably your best bet for this:
usort($array, function($a, $b) {
if (empty($a['position']) && !empty($b['position'])) {
return 1;
}
else if (!empty($a['position']) && empty($b['position'])) {
return -1;
}
else {
return strcmp($a['name'], $b['name']);
}
});
Anonymous functions were introduced in PHP 5.3.0. If you're using an earlier version you can just define a regular function instead:
function cmp($a, $b) {
if (empty($a['position']) && !empty($b['position'])) {
return 1;
}
else if (!empty($a['position']) && empty($b['position'])) {
return -1;
}
else {
return strcmp($a['name'], $b['name']);
}
}
usort($array, 'cmp');
You'll probably want to try usort so you can use a custom sorting function. In the sorting function you can check a["position"] vs b["position"] in the way you describe.

Categories