Getting the array index key to variable - 2D PHP array - php

I have searched for many places for an answer I couldn't find one, so please help me sort out this. - Thanks in advance
I have an Json String
{"first":{"val":100},"second":{"val":200},"third":{"val":300}}
which has been decoded and that has been saved in an php array
$arr = json_decode($json, true);
Now I tried to obtain those first, second, etc... values to concatenate with an sql query, but I couldn't get this sorted, so far I have tried like below,
foreach ($arr as $assoc) {
foreach ($assoc as $value) {
$val=$value+0;
$sqlI = "UPDATE tblName SET fieldName = ".$val." WHERE fieldName1=".$assoc;
$conn->query($sqlI);
}
}
*Note: the fieldName1 will have unique values..
I am getting Notice: Array to string conversion error I understand this due to $assoc is an array type but how to get the key from this array?

Your array would look like this:
$arr = Array(
'first' => array(
'val' => 100
),
'second' => array(
'val' => 200
),
'thirth' => array(
'val' => 300
),
);
You can access them like so:
echo $arr['first']['val']; // 100
Loop trough them like so:
foreach($arr as $val){
echo $val['val']; // 100, 200, 300.
}
Or with key:
foreach($arr as $key => $val){
echo "current key: '$key' with val '". $val['val'] ."'";
}

Related

how do i loop through an associative array with multiple values

I just started learning php and I have this issue. I'm trying to loop through this array to get the total value of each key and output the student with the highest number. I'd really appreciate your inputs
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
The expected output should be Grace but i can't seem to get it to work.
You don't have to loop. Just calculate all the totals
$totals = array_map('array_sum', $students);
then output the key of the array with the maximum total.
echo array_keys($totals, max($totals))[0];
Something like this maybe assuming all grades will be positive
$students = array(
'Mary' => [20,45,12],
'Grace' => [40,78,56],
'John' => [61,37,58]
);
$highest_grade = 0;
$higest_person = "";
foreach($students as $key => $value) {
$max = max($value);
if ($highest_grade <= $max) {
$highest_grade = $max;
$highest_person = $key;
}
}
echo $highest_person . '->' . $highest_grade;
Output is using http://phptester.net/
Grace->78

How to decode json, group by a column value, and sum values in each group? [duplicate]

This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 1 year ago.
I have data in MySQL. The data is created by json datas. But I can't change to array from data keys. I want to set this data in order and according to the number of stock.
[
{"size":"36","stock":"1"},
{"size":"37","stock":"2"},
{"size":"38","stock":"1"},
{"size":"40","stock":"1"},
{"size":"36","stock":"1"},
{"size":"37","stock":"3"},
{"size":"38","stock":"2"},
{"size":"39","stock":"3"},
{"size":"40","stock":"2"}
]
I want change to:
array(
'36' => '2',
'37' => '5',
'38' => '3',
'39' => '3',
'40' => '3',
)
I wrote this function but it only returns true and I feel it could be more refined:
function shoesizes($json,$key='size')
{
$array = json_decode($json);
$result = array();
$sum = 0;
$i=0;
foreach((array) $array as $val) {
if(array_key_exists($key, $val)){
$result[$val->$key][] = (array)$val;
}else{
$result[""][] = $val;
}
}
$arrsi = array();
foreach ($result as $k => $v) {
$sum = 0;
foreach ($v as $c => $d) {
$sum += $d['stock'];
}
$arrsi[$k]= $sum;
}
return ksort($arrsi);
}
Decode then iterate the array. If the first occurrence of size store the integer value, if not add the new value to the stored value. When done, sort by the result array keys.
Code: (Demo)
$json = '[
{"size":"36","stock":"1"},
{"size":"37","stock":"2"},
{"size":"38","stock":"1"},
{"size":"40","stock":"1"},
{"size":"36","stock":"1"},
{"size":"37","stock":"3"},
{"size":"38","stock":"2"},
{"size":"39","stock":"3"},
{"size":"40","stock":"2"}
]';
$array = json_decode($json, true);
foreach ($array as $row) {
if (isset($result[$row['size']])) {
$result[$row['size']] += $row['stock'];
} else {
$result[$row['size']] = (int)$row['stock'];
}
}
ksort($result);
var_export($result);
Output:
array (
36 => 2,
37 => 5,
38 => 3,
39 => 3,
40 => 3,
)
Code Review:
ksort() returns a boolean result. By writing return ksort($arrsi);, you can only receive true or false (and false can only happen when there is a failure). http://php.net/manual/en/function.ksort.php Once you write ksort($arrsi); then return $arrsi; then your function returns the desired result.
You declare, but don't use $i so that line can be safely removed.
The first declaration of $sum = 0; isn't necessary because you redeclare the variable later in your second loop.
Your first loop creates an unnecessarily bloated data structure. Assigning the size values as keys is certainly the right step. Storing each set of date as a subarray of the new key is more than what you need. This causes you to have to follow up with a nested loop.

How to add $_POST values in a multi-dimensional array (PHP)?

I know there may be sources for this out there but I'v tried everything and I'm still not getting the proper solution. That why I'm asking for you help out here.
I have a $_POST array and I want to put values in a an array. Here is the final out I want:
$response = [
['category' => 2, 'value' => "june"],
['category' => 5, 'value' => "may"],
['category' => 8, 'value' => "april"]
]
Here is the catch,the $_POST contains a value of an integer with a space in between and then a string eg '2 june', '5 may' etc
When I get this value, I split it using explode then I try to add the individual values into the response array. This is only adding just one result.
What I tried:
$response = [];
foreach ($_POST as $key => $value) {
$split = explode(" ", $value);
$result = ['category' => $split[0], 'value' => $split[1]];
$response[] = $result;
}
for some reason, the results are not as suggested above. Any ideas and suggestion will be appreciated.
Basically, problem is in the $_POST. This is global array with submitted key-values data. You should NOT use
foreach ($_POST as $key => $value) {
for parsing your data without any checks. This data is submitted by user, and not always they will have format you're waiting for.
For example, if you have a variable "dates" in your HTML form, you should be ready that $_POST['dates'] will be an array of all of your '5 june', '7 july', etc. Don't forget to check and validate all user data you received. It's important by security reason too.
Your code (foreach body, without condition) is ok, I've checked it. Try to set print_r() before explode() you will see that your're working with an array, not with a string.
Your question doesn't have an issue with processing the data into the correct resulting array. The onus falls on $_POST not holding the expected data.
All answers to this question are powerless to fix your $_POST data because no html form was supplied with your question. The only potential value that can be offered is to refine your array building process.
Here are two methods that improve your process by reducing the number of declared variables:
Demonstration uses $a=array('2 june','5 may','8 april'); to represent your $_POST array.
One-liner in a foreach loop:
foreach($a as $v){
$r[]=array_combine(["category","value"],explode(" ",$v));
}
One-liner with no loop:
$r=array_map(function($v){return array_combine(["category","value"],explode(" ",$v));},$a);
Using either process the resulting $r will be:
array (
0 =>
array (
'category' => '2',
'value' => 'june',
),
1 =>
array (
'category' => '5',
'value' => 'may',
),
2 =>
array (
'category' => '8',
'value' => 'april',
),
)
References for used functions:
explode() , array_combine() , array_map()
Try this one:
$response = [];
// just for example use this one
$data = "2 june, 5 may, 7 july";
$temp = explode(",", $data);
// and you can use this one for your case
/*$data = $_POST['var_name']; // var_name is your variable name from $_POST
$temp = explode(",", $data);*/
foreach ($temp as $key => $value) {
$split = explode(" ", trim($value));
foreach ($split as $val) {
$result = ['category' => $split[0], 'value' => $split[1]];
}
$respon[] = $result;
}
echo "<pre>";
echo print_r($respon);
echo "</pre";
the output:
Array
(
[0] => Array
(
[category] => 2
[value] => june
)
[1] => Array
(
[category] => 5
[value] => may
)
[2] => Array
(
[category] => 7
[value] => july
)
)
$response = array();
foreach ($_POST as $key => $value) {
$split = '';
$split = explode(" ", $value);
$result = array('category' => $split[0], 'value' => $split[1]);
$response[] = $result;
}

PHP - array key within array value

I have a PHP array like this:
$arr = array(
'id' => 'app.settings.value.id',
'title' => 'app.settings.value.title',
'user' => 'app.settings.value.user'
);
I want to remove '.id', '.title' and '.user' in the array values. I want to insert the key of this array at the end of the value. I know, that I can get an array key by passing an array and a value to 'array_search', but I want the key within this one array definition - at the end of it's value. Is this possible?
I don't like this, but I guess it's simple and works:
$arr = array(
'id' => 'app.settings.value',
'title' => 'app.settings.value',
'user' => 'app.settings.value'
);
$result = array();
foreach ($arr AS $key => $value) {
$result[$key] = $value . '.' . $key;
}
You're storing app.settings.value which is the same for all array items, so personally I'd prefer:
$arr = array(
'id',
'title',
'user'
);
function prepend_key($key)
{
return 'app.settings.value.' . $key;
}
$result = array_map('prepend_key', $arr);
With $result containing:
array(
'app.settings.value.id',
'app.settings.value.title',
'app.settings.value.user'
);
At the end of the day, either works :)

PHP fetch the value from JSON

I have the customer details in the following format
How do i fetch the customer id is '5' from the output.
json_decode(array)
Result:
stdClass Object (
[5] => stdClass Object (
[email] => siddareddy.vishnuvardhanreddy#gmail.com
[firstname] => vishnu
[lastname] => siddareddy
)
)
You can cast it to an array and then get the first key:
$key = key( (array) $result_object );
$array = json_decode($json, true);
foreach ($array as $key => $value)
{
echo $key; //or use $value array to get the rest of its info
}
Please note that your first line cannot yield the second line as output. The first line should return an array, while the second code block is an object.
You can loop through all keys and values of your Array/Object and get the '5' that way:
foreach( $decodedjson as $key => $val ) {
#Key is: 5
echo "Key is: {$key}";
#Val['firstname'] is: vishnu
echo "Val['firstname'] is: {$val['firstname']}";
}
You can access the numeric property like this
<?php
$data = array(
"5" => array(
'email' => 'siddareddy.vishnuvardhanreddy#gmail.com',
'firstname' => 'vishnu',
'lastname' => 'siddareddy'
)
);
$json = json_encode($data);
$obj = json_decode($json);
var_dump($obj->{5}->email);
$obj->{5}->email, this the trick.
If you want to invert the array from id to that array from say, email to id:
$result = json_decode($array, true);
// Change email to something else if you want another key
$inversecopy = array_flip(array_map(function($val) { return $val['email']; }, $result));
Example in phpfiddle

Categories