I have a multi dimensional array built dynamically.
Is it possible to get the value of an element by using another element.
e.g : search with idQ = 26 and get in return value its neighbor element values like :: idA=>49 and A=>500-10000
[0]=>
array(5) {
["idQA"]=>
string(3) "194"
["idQ"]=>
string(2) "26"
["Q"]=>
string(58) "Imposition supérieur
à 2500€ d’impôts annuel"
["idA"]=>
string(2) "49"
["A"]=>
string(10) "5000-10000"
}
[1]=>
array(5) {
["idQA"]=>
string(3) "173"
["idQ"]=>
string(2) "22"
["Q"]=>
string(20) "Si oui, laquelle(s):"
["idA"]=>
string(2) "32"
["A"]=>
string(7) "Voiture"
}
Example array :: https://gist.github.com/anonymous/9234703
Yes, like:
$founded = 0;
foreach($my_array[1] as $key => $val) {
if ($val == "something_to_search") {
$founded = $key;
break;
}
}
$before = $my_array[1][$founded-1];
$after = $my_array[1][$founded+1];
Related
I have this array :
array(8) {
[0]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(5) "82.00"
}
[1]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(5) "62.00"
}
[2]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(6) "182.00"
}
[3]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(6) "162.00"
}
[4]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(6) "103.00"
}
[5]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(5) "63.00"
}
[6]=>
array(2) {
["ticket_type"]=>
string(9) "normal"
["ticket_price"]=>
string(6) "203.00"
}
[7]=>
array(2) {
["ticket_type"]=>
string(9) "cheaper"
["ticket_price"]=>
string(6) "163.00"
}
}
I want to get the min and max price for "normal" and "cheap" ticket category, there will be more ticket categories, so can't hard code it, will get from DB, how can I do that? I'm using PHP 5.6 now, need export as array or json, Let me know if need more details.
Thank you
You can do it at the SQL level:
SELECT MIN(ticket_price) AS min_ticket_price, MAX(ticket_price) as max_ticket_price, ticket_type
FROM {your_table_name}
WHERE {your_conditions}
GROUP BY ticket_type
If you still want to do it in PHP you can just loop the array and to sort the ticket types then get the min and max values.
foreach($arr as $ticket){
$new[$ticket["ticket_type"]][] = $ticket["ticket_price"];
}
// loop the new array to only get the max and min values of each ticket type
foreach($new as $key => $n){
$res[$key]["max"] = max($n);
$res[$key]["min"] = min($n);
}
output:
array(2) {
["normal"]=>
array(2) {
["max"]=>
string(6) "203.00"
["min"]=>
string(5) "82.00"
}
["cheaper"]=>
array(2) {
["max"]=>
string(6) "163.00"
["min"]=>
string(5) "62.00"
}
}
https://3v4l.org/RcCHZ
Here is a solution to do on the php level:
$prices = [
["ticket_type"=>"normal", "ticket_price"=>"82.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"62.00"],
["ticket_type"=>"normal", "ticket_price"=>"182.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"162.00"],
["ticket_type"=>"normal", "ticket_price"=>"103.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"63.00"],
["ticket_type"=>"normal", "ticket_price"=>"203.00"],
["ticket_type"=>"cheaper", "ticket_price"=>"163.00"],
];
// STEP:1 group by ticket types
$grouped_array = [];
foreach($prices as $price) {
$ticket_type = $price["ticket_type"];
$grouped_array[$ticket_type][] = $price["ticket_price"];
}
/*
$grouped_array = [
"normal" => ["82.00", "182.00", "103.00", "203.00"],
"cheaper => ["62.00", "162.00", "63.00", "163.00"]
];
*/
function minMax($type_array) {
$min_max = ['min'=> min($type_array), 'max'=>max($type_array)];
return $min_max;
}
// STEP 2: find min and max in each category
$min_max = [];
foreach($grouped_array as $type => $prices) {
$min_max[$type] = minMax($prices);
}
/*
$min_max = [
"normal" => ["min"=>"82.00", "max"=>"203.00"],
"cheaper => ["min"=>"62.00", "max"=>"163.00"]
];
*/
However, doing it on the database layer is best in your case. this answers "How to get max and min value in a multidimensional array".
What is the shortest way to change multiple values in array key that has a specific value in it?
For example, I have this array:
array(2) {
[0]=>
array(5) {
["state"]=>
string(6) "active"
["payer_mail"]=>
string(12) "mail#none.com"
["start"]=>
string(12) "06/05/2015"
["end"]=>
string(8) "08/07/2017"
["price"]=>
string(8) "45.00"
["keystring"]=>
string(8) "493457025"
}
[1]=>
array(6) {
["place"]=>
string(2) "47"
["state"]=>
string(8) "canceled"
["payer_mail"]=>
string(12) "mail#none.com"
["start"]=>
string(9) "20/8/2014"
["end"]=>
string(10) "20/10/2017"
["price"]=>
string(5) "95.00"
["keystring"]=>
string(8) "34879205"
}
}
And I want to change the "state" value of the key that has "34879205" value for his "keystring" sub-key.
You can use foreach():-
foreach($array as &$value) {
if ($value['keystring'] == '34879205'){
$value['state'] = "";//change value here
}
}
Output:- https://eval.in/838789
Another way i found is:
$key = array_search('34879205', array_column($array, 'keystring'));
$array[$key]['state'] = 'newvalue';
You can use array_map function
$result = array_map(function ($element) {
if ($element['keystring'] === '34879205') {
$element['state'] = 'new_state';
}
return $element;
}, $array);
The following code gives the array below, however I need it formatted differently (stated after the array), so it will work for a javascript function I've already written.
$sql = "SELECT towhich, duedate, amount FROM sales WHERE email = '$email' ORDER BY duedate ASC";
$result = mysqli_query($conn, $sql);
$dbarray = array();
while($row = mysqli_fetch_assoc($result)) {
$dbarray[] = $row;
}
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
0 => $values['amount'],
1 => $values['towhich']
);
$cnt ++;
}
//Now it's grouped by date
Array output:
array(5)
{
["02"]=> array(2)
{
[0]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
[1]=> array(2) { [0]=> string(2) "30" [1]=> string(9) "the co op" }
}
["03"]=> array(1)
{
[2]=> array(2) { [0]=> string(2) "50" [1]=> string(9) "the co op" }
}
["04"]=> array(1)
{
[3]=> array(2) {[0]=> string(2) "40" [1]=> string(9) "the co op" }
}
["05"]=> array(2)
{
[4]=> array(2) {[0]=> string(2) "10" [1]=> string(9) "the co op" }
[5]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
["06"]=> array(1)
{
[6]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
}
The key index value for array should not be, for example, ['02'], but, being the first in the containing array, [0], like normal; and '03' should be [1].
I've looked around a lot, indeed it helped with what bit of code I've produced, however all answers seem to deal with changing the key value further inside the large array. I'm new with multidimensional arrays, btw. Thanks in advance.
In case you're wondering why I've done it like so, so far, it's because each first array should correspond to a different month; that's why I've ordered by date and all that.
If I got you right, you can use: array_values :
$graph = array_values($graph);
so "02" will be 0, "03" will be 1 , ... etc.
$key in your foreach will be the relative record number that the row occurs in the query.
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
$graph[$key] = array (
$month,
$values['amount'],
$values['towhich']
);
$cnt ++;
}
Im new to json & php and I'm having some issues with json into php string
My json string looks like this
{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}
So Far i have created my string
$json_raw = '{"status":"OK","cards": [{"id":100001,"name": .....
Decoded the json
$arr = json_decode($json_raw, TRUE);
I var_dump($arr);
then it returns
array(2) { ["status"]=> string(2) "OK" ["cards"]=> array(4) { [0]=> array(8) { ["id"]=> int(100001) ["name"]=> string(6) "batman" ["image"]=> int(11111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T11:37:07Z" } [1]=> array(8) { ["id"]=> int(100002) ["name"]=> string(8) "superman" ["image"]=> int(111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:30:09Z" } [2]=> array(8) { ["id"]=> int(100003) ["name"]=> string(8) "catwoman" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:39:42Z" } [3]=> array(8) { ["id"]=> int(100004) ["name"]=> string(4) "bane" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-09-08T12:56:04Z" } } }
Now all I want to do is be able to use this data
e.g if name = batman then
I know this is a stupid question but I am struggling :(
Thank in Advance
json_decode() with TRUE as second parameter gives you an associative array. You need to access the correct index to do what you want.
To list the complete associative array with nice formatting, you can do:
echo '<pre>', print_r($arr), '</pre>';
Now, to access the name in your array:
$man = $arr['cards'][0]['name'];
To check if it's Batman (yay!):
if( isset($man) && $man == 'batman' ) {
# code ...
}
For getting the name of all similar names:
$man = $json['cards']['0']['name'];
for ($i=0; $i < count($json['cards']); $i++) {
echo $json['cards'][$i]['name']."\n";
}
See it live!
when you got the array
$arr = json_decode($json_raw, TRUE);
then check if cards key exist
if(array_key_exists('cards', $arr)){
foreach($arr['cards'] as $key=>$val){
echo $key; ///name, id..
echo $val; /// batman,...
if($key == 'name' && $val =='batman'){
//-------do your stuff
}
}
}
Try with:
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
EDIT:
Ok, so this worked for me using code above, try it yourself if you want:
<?php
$json_raw = '{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}';
$arr = json_decode($json_raw, TRUE);
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
?>
I need to get the objects information for "label", "name" where value=true in a PHP variable and not were value=false.
How is this done with this JSON array?
If I make a var_dump of the JSON I get this:
array(8) {
[0]=>
object(stdClass)#8 (3) {
["label"]=>
string(4) "Name"
["name"]=>
string(7) "txtName"
["value"]=>
bool(true)
}
[1]=>
object(stdClass)#9 (3) {
["label"]=>
string(6) "E-mail"
["name"]=>
string(8) "txtEmail"
["value"]=>
bool(true)
}
[2]=>
object(stdClass)#10 (3) {
["label"]=>
string(12) "Phone Number"
["name"]=>
string(8) "txtPhone"
["value"]=>
bool(false)
}
[3]=>
object(stdClass)#11 (3) {
["label"]=>
string(19) "Mobile Phone Number"
["name"]=>
string(14) "txtMobilePhone"
["value"]=>
bool(false)
}
}
$arr = array();
$i = 0;
foreach($json as $key => $items) {
if($items->value == true) {
$arr[$i]['label'] = $items->label;
$arr[$i]['name'] = $items->name;
$i++;
}
}
You can decode it as an object or an array, in this example I use an array.
First you want to take the JSON encoded information and decode it into a PHP array, you can use json_decode() for this:
$data = json_decode($thejson,true);
//the Boolean argument is to have the function return an array rather than an object
Then you can loop through it as you would a normal array, and build a new array containing only elements where 'value' matches your needs:
foreach($data as $item) {
if($item['value'] == true) {
$result[] = $item;
}
}
You then have the array
$result
at your disposal.
Simplification of the suggestions proposed by users JohnnyFaldo and som:
$data = json_decode($thejson, true);
$result = array_filter($data, function($row) {
return $row['value'] == true;
});