I want to foreach $key equal to $values to return the $called that matches the $key.
foreach($value as $values);
foreach($json['values'] as $key => $called) {
if($key == $values) {
$myreturns[] = $called;
}
}
return json_encode($myreturns, true);
I have a select multiple which value is a number and if not a number on registration it fails (to stop people changing values).
I populate it with the following json
{
"values": {
"1": "Black",
"2": "Blue",
"3": "Brown",
"4": "Grey",
"5": "Green",
"6": "Hazel",
"7": "Violet"
}
}
if somebody chose black and blue, the values will be 1 and 2.
For example I want foreach $key so the json above if that number is equal to "1" to return the $called that is related to the $key.
I know this is wrong but I want something like this
foreach($key == $values) {
$myreturns[] = $called;
}
Close. use array_push to push the results into a new array, then json encode that.
// json decode into associative array
$values = json_decode($json, true);
// init results
$results = array();
foreach($values as $key => $value) {
if($called == $key) {
array_push($results,$value);
}
}
$result = json_encode($result);
return $result;
Also note that if you want to get an item within a json array, it is easier to just reference it within the array:
$array = json_decode($json,true);
$item = $array[$key];
Related
I have some difficulties with PHP Arrays. I'm trying to foreach some values, order them with array_multisort and foreach them again so I can create some kind of code.
So what I'm doing is, I'm passing json object as:
"options": [
{"key": "Ships From", "value": "Russia"},
{"key": "Color", "value": "Green"},
{"key": "Size", "value": "M"},
{"key": "Material", "value": "Flex"}
],
So this is received from frontend, and I'm foreaching them like so:
public function findAttribute($product_id, $values)
{
$array = array();
foreach ($values as $key => $value) {
$getAttr = $this->attribute($value['key']);
$getAttrValue = $this->attributeValue($getAttr->id, $value['value']);
$code = $getAttr['label'] . '=' . $getAttrValue['value'];
$collection = array_push($array, array($getAttr->default_order, $code));
}
array_multisort($array, SORT_ASC);
}
As you can see I have $getAttr and $getAttrValue, that selects values from database, in order to get default_order (integer) so I can sort them with multisort.
So actually this code works as expected, and when I write (after multisort) like:
foreach($array as $key => $value){
echo $value[1] .'/';
}
I have expected value, but when I call that function it gives me that it returns NULL, if I change echo to return, I have only first array. If I try like
foreach($array as $key => $value){
$code = $value[1] .'/';
}
return $code;
No success as well.
What should I do?
Because in each iteration you assign a new value to $code so you will only get the last $value [1] in the array (after arranged).
If you want to return a string concatenating all values, you could do as this:
$code = '';
foreach($array as $key => $value){
$code .= $value[1] .'/';
}
return $code;
$code = array();
foreach($array as $key => $value){
$code = $value[$key] .'/';
}
return $code;
Implement your code i hope that will work.
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
I have a JSON that I would want to get the values from. However, the key values are typical key. They are not one worded.
[
{
"quality-of-service": "Good"
},
{
"quality-of-staff": "Great"
},
{
"quality-of-communication": "Excellent"
},
{
"value-for-money": "Excellent"
}
]
How do I get the values for the keys.
After decoding $array = json_decode($json, true), the first value would be $array[0]['quality-of-service'] which is not a good way to do it. You could loop:
foreach($array as $values) {
echo key($values) . " is " . current($values);
}
Or you can flatten the array:
$array = array_merge(...$array);
Then use $array['quality-of-service'] or loop it:
foreach($array as $key => $value) {
echo "$key is $value";
}
This is a schema generator that displays the key:value pair
"default": [
{
"one": "u0001u0000u0000u0000",
"two": "u0002u0000u0000u0000",
"three": "u0003u0000u0000u0000"
}
]
What I would like to print out is "default": [{"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}]
Similarly if it is an object for instance:
"default": [ "a":
{
"one": "u0001u0000u0000u0000",
"two": "u0002u0000u0000u0000",
"three": "u0003u0000u0000u0000"
}
]
concatenate only values and print like this:
["a": {"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}]
Sample Code Test:
// this method gets the value entered by user in json format. The user can put in a nested json format as well. The above examples that I mentioned works.
it then calls for scanForNestedType method which scans whether the format contains any array, array>, map etc...
Once it scans for nested type, it internally calls $this->encodeValues($unit)which converts the values entered by user from integer to bytes.
Here is an example:
User enters array
[{"one": 1, "two": 2, "three": 3}]. After conversion, the result would be as follows:
[
{
"one": u0001u0000u0000u0000,
"two": u00002u0000u0000u0000,
"three: u0003u0000u0000u0000
}
]
Now I am getting the values correctly for each key. All I need is to print in this format:
[
{
u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000
}
]
private function jsonDecode(array $value)
{
$strValue = $value['value'];
$jsonValue = json_decode($strValue);
$this->scanForNestedType($jsonValue);
return $jsonValue;
}
private function scanForNestedType(&$value)
{
foreach ($value as $key => &$unit) {
if (is_array($unit) || is_object($unit)) {
$this->scanForNestedType($unit);
} else {
$value->$key = $this->encodeValues($unit);
}
}
}
private function encodeValues(int $value)
{
$encodedValue = '';
$bytesArray = unpack("C*", pack("V", $value));
foreach ($bytesArray as $byte) {
$encodedValue .= sprintf('u%04x', dechex($byte));
}
return $encodedValue;
}
If I get a working example then it would be great!
You can use json_decode to convert json to an array. Then implode sub-array ['one'....] using foreach loop.
snippet
$json1 = '[{"one": "u0001u0000u0000u0000", "two": "u0002u0000u0000u0000", "three": "u0003u0000u0000u0000"}]';
$json2 = '[{ "a": { "one": "u0001u0000u0000u0000", "two": "u0002u0000u0000u0000", "three": "u0003u0000u0000u0000" } }]';
$arr1 = json_decode($json1,true);
$arr2 = json_decode($json2,true);
foreach($arr1 as $data){
$default1[] = implode($data);
}
$default1 = json_encode($default1, JSON_FORCE_OBJECT);
foreach($arr2 as $key => $child){
foreach($child as $childKey => $data){
$default2[$childKey] = implode($data);
}
}
$default2 = json_encode($default2, JSON_FORCE_OBJECT);
print_r($default1);
print_r($default2);
Output
{"0":"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}
{"a":"u0001u0000u0000u0000u0002u0000u0000u0000u0003u0000u0000u0000"}
Live Demo
You can now json_decode $default1, $default2 to get php object/array.
This question already has answers here:
How do I encode a PHP array to a JSON array, not object?
(4 answers)
Closed 8 years ago.
I'm trying to remove numbers that is being display in my json 2d array. I first had an 2d array that is dynamic and deletes elements from that array. Then it converts the array to a json 2d array. The problem is I don't want the numbers at the start.
Like below
[
"1": {"StateName":"Alaska","StateAbbr":"AK"},
"2": {"StateName":"Alabama","StateAbbr":"AL"},
"3": {"StateName":"Arkansas","StateAbbr":"AR"},
"4": {"StateName":"Arizona","StateAbbr":"AZ"},
"5": {"StateName":"California","StateAbbr":"CA"},
"6": {"StateName":"Colorado","StateAbbr":"CO"},
"7": {"StateName":"Connecticut","StateAbbr":"CT"}
]
I would like it to be like this
[
{"StateName":"Alaska","StateAbbr":"AK"},
{"StateName":"Alabama","StateAbbr":"AL"},
{"StateName":"Arkansas","StateAbbr":"AR"},
{"StateName":"Arizona","StateAbbr":"AZ"},
{"StateName":"California","StateAbbr":"CA"},
{"StateName":"Colorado","StateAbbr":"CO"},
{"StateName":"Connecticut","StateAbbr":"CT"}
]
With out the numbers. How can I do this?
I tried mysql_fetch_assoc but it doesn't work it.
$arr = array();
while($row = mysql_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode($arr);
I found out how to remove the keys from the 2d array once converted to a json. Create functions to do this.
function remove_json_keys($array) {
foreach ($array as $k => $v) {
if (is_array($v)) {
$array[$k] = $this->remove_json_keys($v);
} //if
} //foreach
return $this->sort_numeric_keys($array);
}
function sort_numeric_keys($array) {
$i=0;
foreach($array as $k => $v) {
if(is_int($k)) {
$rtn[$i] = $v;
$i++;
} else {
$rtn[$k] = $v;
} //if
} //foreach
return $rtn;
}