Finding the largest ID in this PHP associative array - php

I have a query which returns several thousands objects from my database. The result set is an array of associative arrays. An example would be something along the lines of:
Array(
Array(
"id" => 500,
"name" => "Bob"
),
Array(
"id" => 2,
"name" => "Cindy"
),
Array(
"id" => 200,
"name" => "Jane"
)
);
In this case I'd need to be able to filter/sort this array to retrieve the id of 500.

Here's one way to do it:
Get the ids into an array (using array_column())
Get the highest value in the array (using max())
This should do the trick:
echo max(array_column($array, 'id'));
Demo

Related

Why are my google actions "suggestions" only showing the last entry?

I am creating a response from my own webhook.
Now i wanted to send the suggestions array, but am struggling with creating an array in an array. How does these need to be set up?
$jsonResponse = json_encode(array(
"session" => array(
"params" => array(
"antA" => "Hello Answer A",
"antB" => "Hello Answer B",
"extrainfo" => "This is some extra information"
)
),
"prompt" => array(
"override" => false,
"firstSimple" => array(
"speech" => "<speak>".$speech."</speak>"
),
"suggestions" => array(
"title" => "aa",
"title" => "bb",
"title" => "cc"
),
)
));
The issue is that prompt.suggestions is specified to take an indexed array of Suggesion objects, that is, an array that maps from numbers to the objects (or just a list, where the numbering is assumed). But you are providing an associative array - that is, mapping a property name to something. Furthermore, your associative array is naming everything the same. Php uses similar syntax for indexed arrays and associative arrays, so it can sometimes be unclear what you actually need.
In this case, that part of your code should probably look something more like this:
"suggestions" => array(
array("title" => "aa"),
array("title" => "bb"),
array("title" => "cc")
)

PHP selecting only 4 from multidimensional array and shuffling

I have the following PHP multidimensional array, I'm looking to try select 4 random items and then show them with the title, image and text. With the code I've used I seem to get a single number which is randomized and not what I need.
<?php
$arr = array(
array(
"image" => "",
"title" => "Open 7 days.",
"text" => "We’re open 7 days a week."
),
array(
"image" => "",
"title" => "Well done",
"text" => "Well done you done great."
),
array(
"image" => "",
"title" => "Rice",
"text" => "Various flavours"
),
array(
"image" => "",
"title" => "Rooms",
"text" => "Roomy rooms for a roomyful time"
),
array(
"image" => "",
"title" => "Keep in touch.",
"text" => "Stay in touchwith us as we'll miss you"
),
array(
"image" => "",
"title" => "Location",
"text" => "We'll show you where we are."
),
array(
"image" => "",
"title" => "The Home",
"text" => "See our home page"
)
);
print_r(array_rand($arr));
If you're picking only one entry, array_rand() returns a single key for a random entry. If you use the num to specify how many keys should be picked, then it returns num number of keys of random entries.
The function only returns the keys of the random entries and not the array chunks itself. You'll have to manually build the array from the returned keys:
// get the random keys
$keys = array_rand($arr, 4);
// initialize result array
$result = array();
// loop through the keys and build the array
foreach ($keys as $k) {
$result[] = $arr[$k];
}
print_r($result);
Update
From a quick benchmark, it seems array_rand() is signficantly faster than using shuffle() for larger arrays. The benchmark was done on an array having 14336 elements with 10000 iterations each.
The results obtained on my dev machine were as follows:
Number of elements in the array - 14336
Number of iterations for each method - 10000
array_rand() version took 4.659 seconds
shuffle() version took 15.071 seconds
The code used for benchmarking can be found in this gist.
No need to loop !
shuffle() and array_slice() does the job.
Simply shuffle your array such that it rearranges the entries , now pick the first 4 items using array_slice.
shuffle($arr);
print_r(array_slice($arr,0,4));
Demo
Read about the $num parameter array_rand()
print_r(array_rand($arr, 4));
To display all:
foreach(array_rand($arr, 4) as $key) {
echo $arr[$key]['text'] ."\n";
//etc
}

MySQL Query multiple results into a single value Array

I have the following array from an API
$arrs = array(
"id" => $ids,
"names" => $names,
"description" => $desc,
"picture_url" => $p_img;
);
The API require this information to work unfortunately I can only have one array per request, so I send this question to the developers:
How can I list multiple item such as:
$arrs= array(
"items1" => array (
"id" => $ids,
"names" => $names,
"description" => $desc,
"picture_url" => $p_img;
)
"items2" => array (
"id" => $ids,
"names" => $names,
"description" => $desc,
"picture_url" => $p_img;
)
"items3" => array (
"id" => $ids,
"names" => $names,
"description" => $desc,
"picture_url" => $p_img;
)
));
And they told me that at the moment is not possible, so, the "important" part of this array is the "names", when it is use with a single item there is no problem I get a single name, done, no problem, but what if I have multiple names? I can send multiple request but that will be seen as a flood or something like... just imaging 300 names = 300 request in one second or so... sure I can put a pause per request but is not efficient...
the API will read something like this...
"id" => 654,
"names" => "John", // <-- Lets look at this...
"description" => "Fancy desc...",
"picture_url" => "http"//domain.com/assets/user/654/av_654_dd.jpg";
So before I output the array I have an SQL Query with a while to display the information...
while ($names = $listnames->fetch_assoc()) {echo $names['names']. ', ';}
This will display... John, Karl, Lisa, Mark... so this same structure I'd love to put it into my array... the thing is I can't put a while after the => ... that would be silly and it wont work...
"id" => 654,
"names" => "John, Karl, Lisa, Mark", // <-- Lets look at this...
"description" => "Fancy desc...",
"picture_url" => "http"//domain.com/assets/user/654/av_654_dd.jpg";
if I need only one name then there is not problem... but in this case I need to put all of the name as a value, so, how can get the result from a WHILE loop.... so that I can use that result elsewhere...
Thank you for taking the time..
while ($names = $listnames->fetch_assoc()) {
$name_array[] = $names['names'];
}
$arrs=array(
"items1" => array (
"id" => $ids,
"names" => implode(', ', $name_array),
"description" => $desc,
"picture_url" => $p_img;
)
);
We don't know how you access to the API.
If this is a REST API, you are able to do only what the developers planned.
If this is a framework or another library, you may edit it.
And you should receive your results like theses:
$arrs = array(
array(
"id" => 1,
"names" => 'MyName',
"description" => 'MyDesc',
"picture_url" => 'MyPic',
),
array(
"id" => 2,
"names" => 'MyName',
"description" => 'MyDesc',
"picture_url" => 'MyPic',
),
);
So if you have full access to the SQL results, to get all results' data, you could do:
$results = array();
while( $row = $listnames->fetch_assoc() ) {
$results[] = $row;
}
If you want to set several possible name in input, the developers should develop that is possible with array of values.
For names, they just have to code: "LIKE '".implode("', LIKE '", $names)."'"
They could also add '%' to allow more values, e.g. 'John' for 'Johnny'.
I think we need more informations to really help you.

Get index of an array

I'm having some problems retrieving data from a multidimensional array. I have something like this:
$Act[0] = array(
"Number" => 23,
"Local" => "woods",
"props" => "swords..."
.....
$Act[1] = array(
"Number" => 27,
"Local" => "castle",
"props" => "swords..."
.....
......
$Story[$day] = array(
"Date" => $SDate,
"Acts" => $Acts
);
What I want to do is to get all the numbers from the Act array and use implode to store it in a mysql db.
I tried array_keys but it doesnt work with multi-dimensional arrays. I dont know if it would be even appropriate for this. So basically I want an array with all the values of "Number" of $Story[1]["Acts"], so it would have to go through:
$Story[1]["Act"][0]["Number"]
$Story[1]["Act"][1]["Number"]
$Story[1]["Act"][2]["Number"]
...
So...
$numbers = array_map(function($act) {
return $act["Number"];
}, $Story[1]["Acts"]);
# 23, 27, ...
Is that what you're asking?

Merging multiple multidimensional arrays

I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.
For example:
Array
(
[companyid] => 1
[employeeid] => 1
[role] => "Something"
[name] => "Something"
)
but every array may have a different ammount of items inside it.
I want to turn all the arrays into one single table with lots of rows. I tried array_merge() but I end up with a table with 8, 12, 16... columns instead of more rows.
So... any ideas?
Thanks
Didn't test it, but you could try the following:
$table = array();
$columns = array('companyid' => '', 'employeeid' => '', 'role' => '', 'name' => '');
foreach($array as $item) {
$table[] = array_merge($columns, $item);
}
This should work since the documentation about array_merge say:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
So you either get the value of the current item or a default value that you can specify in the $columns array.
$array1=Array
(
"companyid" => 1,
"employeeid" => 4,
"role" => "Something",
"name" => "Something",
);
$array2=Array
(
"companyid" => array(2,2,2),
"employeeid" => 5,
"role" => "Something2",
"name" => "Something2"
);
$array3=Array
(
"companyid" => 3,
"employeeid" => 6,
"role" => "Something3",
"name" => "Something3"
);
//Using array_merge
$main_array["companyid"]=array_merge((array)$array1["companyid"],(array)$array2["companyid"],(array)$array3["companyid"]);
$main_array["employeeid"]=array_merge((array)$array1["employeeid"],(array)$array2["employeeid"],(array)$array3["employeeid"]);
for($i=0;$i<count($main_array["companyid"]);$i++)
echo $main_array["companyid"][$i] + "<br />";
for($i=0;$i<count($main_array["employeeid"]);$i++)
echo $main_array["employeeid"][$i] + "<br />";
I've tested the code above and seems right.
You coult also improve this code into a DRY function.

Categories