POST Array through JSON foreach - php

The question:
I have this array coming through a POST field
{"name":"sample","email":"a#sample.co.uk","comments":"test"}
I want to split it apart and run it through an array, so the end result would be
name sample
email a#sample.co.uk
comments test
What I have tried is this:
$a = $_POST['rawRequest'];
$a = json_encode($a);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v <br />";
}
But it doesn't do anything, however when I test it with this variable (over using the POST)
$a = array("name" => 1,"email" => 2,"sample" => 3);
It works as expected.
Trying to understand what is going on
It is obviously because what I am dealing with here is two different types of array. However after endless google'ing I can't find anywhere which explains the difference (of the arrays below basically). So +1 to an explination which makes my relatively newbie mind understand what is happening and why it is wrong
{"name"=>"sample","email"=>"a#sample.co.uk"=>"comments":"test"}
{"name":"sample","email":"a#sample.co.uk","comments":"test"}

$aa Isn't a array, is a JSON:
$a = $_POST['rawRequest'];
$aa = json_encode($a);
Thus, you can't use foreach in $aa.

If you want to decode a json string into an array instead of an object, use the 'Array' flag.
$array = json_decode($json_string, true);

Try as
$data = '{"name":"sample","email":"a#sample.co.uk","comments":"test"}';
$json = json_decode($data,true);
foreach($json as $key=>$val){
echo $key." - ".$val;
echo "<br />";
}
Check the output here
http://phpfiddle.org/main/code/ytn-kp0
You have done as
echo "\$a[$k] => $v <br />";
This would output as
$a[name] => sample
"$a" will be considered as string
You can do the way you are doing but you need to change the echo something as
echo $k ."=>" .$v. "<br />";
Since you are looping the array using foreach and $k will contain the key of the array and $v will be the value !!

I have Json decoded the encoded array and looped it through a foreach below with comments explaining what each part does.
/* The Json encoded array.*/
$json = '{"name":"sample","email":"a#sample.co.uk","comments":"test"}';
/* Decode the Json (back to a PHP array) */
$decode = json_decode($json, true);
/* Loop through the keys and values of the array */
foreach ($decode as $k => $v) {
$new_string .= $k . ' | ' . $v . '<br/>';
}
/* Show the result on the page */
echo $new_string;
The above code returns the following;
name | sample
email | a#sample.co.uk
comments | test
If you want to access the array values one by one you can also use the following code.
/* The Json encoded array.*/
$json = '{"name":"sample","email":"a#sample.co.uk","comments":"test"}';
/* Decode the Json (back to a PHP array) */
$decode = json_decode($json, true);
echo $decode['name'];//returns sample
echo $decode['email'];//returns a#sample.co.uk
echo $decode['comments'];//returns test

Related

Convert a string structured as a Multidimensional Array to array

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested
There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo
To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

PHP Print array values without all the extra "=>" stuff

I have an array and I want to simply print out a list of all the values. Not sure why I can't find the answer to this. I have tried "var_dump" and "Var_export", "TRUE" and "FALSE". Here is my code:
$var = var_export($xyz,TRUE);
print "$var";
But it outputs this:
array (
0 => '700',
1 => '750', etc
I just want this:
700
750
<?php
$a = array (700, 750);
foreach($a as $key => $value)
{
echo $value. "<br>";
}
?>
You can easily print the value of an array using the foreach loop. Here I gave an example for your better help.
foreach ($xyz as $val) {
echo $val . '<br>';
}
?
Have you tried iterating into $xyz using a foreach loop ?
foreach($xyz as $value) {
print "$value \n" }
The \n being a new line.
edit : identical to #PHPNoob's answer
Looks like you are attempting to get the values from an array.
Using a Foreach will loop through the array apply the code to each value until the array is complete.
foreach($xyz as $value){
echo $value . "<br/>";
}

Make string from array in php

I've got this object
[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]
And i want to build a string like this:
"Fressnapf","Whiskas","Purina"
But if the one of the isChecked boolean would be (false for example like this: [{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":false},{"name":"Purina","isChecked":true}] )
then the string should be look like this:
"Fressnapf","Purina"
So i have a $brands object ( json form above) and now what?
// Decode json to PHP array json_decode(<JSON>, true) the second parameter converts to array instead of object
$arrays = json_decode('[{"name":"Fressnapf","isChecked":true},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]', true);
// Create an array to store the output data you want
$checked_names = [];
// Loop through the arrays of properties in your JSON to find out if the value isChecked is true and if so add the name to your checked_names array
foreach ($arrays as $array) {
if (!empty($array['isChecked'])) {
$checked_names[] = $array['name'];
}
}
// Output with surrounding quotation marks.... implode will turn your array into a string with "glue" -- stuff in between the items... so you need the extra quotes on the outside as well
echo '"' . implode('", "', $checked_names) . '"';
// --- Decode the json array.
$array = json_decode('[{"name":"Fressnapf","isChecked":false},{"name":"Whiskas","isChecked":true},{"name":"Purina","isChecked":true}]');
$string = array();
// --- Loop through the array.
foreach($array as $item){
// --- Check to see if item is checked. If it is, stick it into array $string.
if($item->isChecked != false){
$string[] = $item->name;
}
}
// --- Transform $string to an actual string.
$string = implode(', ', $string);
echo $string;

PHP changing array format

I'm trying to change an array format from this
{"updated":"2016-01-28 02:00:02","rate":"0.1898"}
to this
[2016-01-28 02:00 , 0.1898]
I'm getting the first array format from a MySQL query and need to convert to the second format to use in a line chart.
$newVal = array();
foreach ($dbresult as $key => $value) {
$newVal[] = json_encode(array_values($value));
}
echo implode(",", $newVal);
With this new code block i get this format
["2016-01-28 02:00" , "0.1898"]
But still need to get rid of the double quotes, any ideas?
$json = '[{"updated":"2016-01-28 02:00:02","rate":"0.1898"}]';
echo json_encode(array_map(function ($data) {
return [$data->updated, $data->rate];
}, json_decode($json)));
In other words:
JSON-decode it
loop through it
create a new array with updated in the first index and rate in the second
JSON-encode it again
Step 3 is necessary since JSON objects don't guarantee any particular order, so relying on the decoded order of the keys is not reliable; and it also guarantees you get the data you want even if you add more keys to your objects.
Try this code
$string = ' {"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$array = json_decode($string, true);
$str = json_encode(array_values($array));
echo str_replace('"', '', $str);
you should try this
$str ='{"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$data=json_decode($str);
echo '<pre>';
echo 'json decode it returns ojbects<br>';
print_r($data);
echo 'convert object into array<br>';
$data=(array)$data;
print_r($data);
echo 'Your Output<br>';
echo json_encode(array_values($data));

I am trying to turn an array into string, php is confounding me though?

Hi I am trying to write a piece of code that will allow me to read from an array and then output the required text as string
The code in question:
$mytext = (string)$output[0];
$breakup = explode('--', $mytext);
echo "###########################################";
echo $breakup;
This is the first time I've tried doing this and I don't think implode would work.
Could someone shed some light on what I am doing wrong or help me reach an answer?
try something like this:
$myString = "bob-fred-john-sarah-claire-julie-lisa";
$ex = explode("-", $myString);
then to see whats in the $ex array you can print it out like this:
echo "<pre>";
print_r($ex);
echo "</pre>";
to access individual values of the array you use the array index like this (remember arrays start at index 0):
echo $ex[0]; //this will echo bob.
echo $ex[1]; //this will echo fred.
to echo out each part of the $ex array you use something like a foreach loop:
foreach($ex as $index => $value){
echo $value."<br>";
}
To print out the contents of the array individually you can do it this way:
$mytext = (string)$output[0];
$breakup = explode('--', $mytext);
echo "###########################################";
for ($i=0; $i<count($breakup); $i++) {
echo $breakup[$i];
}
An alternative way is with foreach:
foreach ($breakup as $value) {
echo $value;
}
As mentioned by others, print_r can be used for displaying an array in easily readable format:
print_r($breakup);
You can also use it to store a string:
$myvalue = print_r($breakup, true); //note the ,true which will return the value instead of printing it.

Categories