Getting values from key value pairs PHP - php

I have a registration form which saves user data to a text file via the serializable method.
a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}
I can deserialize the data however I am having some trouble extracting the value "Mario" from the key - "name". Code can be seen below:
$array = file_get_contents('user.txt');
$artikel = unserialize($array);
foreach ($artikel as $item ){
echo $item['name'];
}
The error I recieve is Illegal string offset 'name'. Any help would be greatly appreciated.

You have a serialized array of JSON strings.
So try like this
//$array = file_get_contents('user.txt');
$artikel = unserialize('a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}');
//print_r($artikel);
foreach ($artikel as $item ){
$json = json_decode($item);
echo $json->name;
}
PS: Storing a password in plain text is very bad security, storing that in a simple file is even worse security, so I hope system this will never actually be used. PHP provides password_hash()
and password_verify() please use them.

You need to json_decode after foreach with true as a second parameter then you will get array as you want..
<?php
$arr = 'a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}';
$artikel = unserialize($arr);
foreach ($artikel as $item ){
$response = json_decode($item, true);
echo $response['name'];
}
?>

Related

PHP extract key-value in array json and restructure

Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.

how to Access to nested items in JSON with foreach PHP?

I have the following JSON structure
{"Id":"1","Persons":[{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}
How I can have acces or read the item inside the nest? For example if I just want the value of time for Carl or all information about Carl. Till now I just can get without a problem the single item in the collection 'Id'. The rst nested items not.
I tryed with json_decode like this:
if( $_POST ) {
$arr['Id'] = $_POST['Id'];
$arr['NP'] = $_POST['NP'];
$jsdecode = json_decode($arr);
foreach ($jsdecode as $values){
echo $values->Time;
}
Can PLEASE somebody help me?
if( $_POST ) {
$arr['Id'] = $_POST['Id'];
$arr['NP'] = $_POST['NP'];
$jsdecode = json_decode($arr,true);
foreach ($jsdecode as $values){
echo $values->Time;
}
Adding 'true' to json_decode converts it to array
You are processing it correct , Just add true as the second parameter to json_decode which will be converted to an Array like
$jsdecode = json_decode($arr,true);

convert an array of arrays to json

i want to convert this array as shown below
array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
into this format:
"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}}
I am using PHP and not able to figure out how can i do this. I have used json_encode. but the results are not correct.I am using PHP as my language.
thanks in advance
Before converting into json, you should change the array:
$array_countries_formated = array();
foreach ($array_countries as $item)
{
$array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label'];
}
echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT);
Result:
{"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}}
Try this...
<?php
$array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
$jsonString = json_encode($array_countries);
print_r($jsonString);
?>
Result:
{"20":{"cntryValue":"3","cntryLabel":"Egypt","value":"7","label":"Tanta"},"21":{"cntryValue":"3","cntryLabel":"Egypt","value":"1000","label":"Other"},"22":{"cntryValue":"80","cntryLabel":"India","value":"0","label":"All"},"23":{"cntryValue":"80","cntryLabel":"India","value":"1","label":"Ahmedabad"}}
If I understand your requested output correctly, the following should do the trick:
$result = array();
foreach ($array_countries as $country) {
$cntryValue = $country["cntryValue"];
if (!array_key_exists($cntryValue, $result)) {
$result[$cntryValue] = array();
}
$result[$cntryValue][$country["cntryLabel"]] = array();
$result[$cntryValue][$country["cntryLabel"]][$country["value"]] = $country["label"];
}
echo json_encode($result) . "\n";
A little explanation: the array provided ($array_countries) is formatted differently as compared to your requested output. Therefore, it should be converted. That is what the foreach loop does. The formatted result can be converted to json using the json_encode function.

json decode with an array in php

I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.
If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}

Add values to array via foreach

I'm trying to add values to an array via foreach but it only returns the word "Array" not the actual strings.
$msg = array();
foreach ($results as $result) {
$inventory = $result->qoh;
$inventoryOrder = $result->qo;
$product = $result->item;
$totalinv = $inventory+$inventoryOrder;
if ($inventory <= $threshold) {
$message = "Inventory for $product has fallen beneath threshold. $inventory remaining.\n";
$msg[] = array($message);
}
}
print (array_values($msg));
I've tried a few different ways and everytime it returns the word "Array"
You should use print_r, not print. print is for stings only. Try this:
echo '<pre>'; print_r(array_values($msg)); echo '</pre>';
Use var_dump to see the values.
var_dump (array_values($msg));
var_dump will alway show you the type of the result too. Helps a lot in debugging. (Looking at your code, I'm assuming you are doing the same).
I think you need to change the following code:
$msg[] = array($message);
to
array_push($msg, $message);

Categories