PHP JSON get key and value - php

I have the following JSON format:
{
"S01": ["001.cbf", "002.cbf", "003.cbf", "004.cbf", "005.cbf", "006.cbf", "007.cbf", "008.cbf", "009.cbf"],
"S02": ["001.sda", "002.sda", "003.sda"],
"S03": ["001.klm", "002.klm"]
}
I try using this code:
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
foreach($json as $key => $val) {
if ($key) { echo 'KEY IS: '.$key; };
if ($val) { echo 'VALUE IS: '.$value; };
echo '<br>';
}
But i got empty results...i need to get output like this:
KEY IS: S01
VALUE IS: 001.cbf
VALUE IS: 002.cbf
VALUE IS: 003.cbf
VALUE IS: 004.cbf
VALUE IS: 005.cbf
VALUE IS: 006.cbf
VALUE IS: 007.cbf
VALUE IS: 008.cbf
VALUE IS: 009.cbf
KEY IS: S02
VALUE IS: 001.sda
VALUE IS: 002.sda
VALUE IS: 003.sda
KEY IS: S03
VALUE IS: 001.klm
VALUE IS: 002.klm
This i need so that i can generate ul and li elements using value and key name...this is JSON format that is stored in mysql database and is read to php script that needs to parse the JSON in the above output so that i can create ul and li elements using output.
I try to do foreach but i got empty results? I know when i got value that i need to do explode string using explode(', ', $value) but i can't get $value and $key to be read as needed in PHP.

This solves your problem, you had to cast $json to array because it was considered as an stdClass object ;)
<?php
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
foreach($json as $key => $val) {
echo "KEY IS: $key<br/>";
foreach(((array)$json)[$key] as $val2) {
echo "VALUE IS: $val2<br/>";
}
}
?>
Try It Online!
I recommend you to use the function var_dump($var) next time you run into troubles, it will help you to figure out what's wrong.

$json = '{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}';
$array = json_decode($json, true);
foreach($array as $key => $val) {
echo 'KEY IS:'.$key.'<br/>';
foreach($val as $_key => $_val) {
echo 'VALUE IS: '.$_val.'<br/>';
}
}

If you performed a var_dump($json) to observe the result you would see it looks like this...
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
var_dump($json);
object(stdClass)[1]
public 'S01' =>
array (size=9)
0 => string '001.cbf' (length=7)
1 => string '002.cbf' (length=7)
2 => string '003.cbf' (length=7)
3 => string '004.cbf' (length=7)
4 => string '005.cbf' (length=7)
5 => string '006.cbf' (length=7)
6 => string '007.cbf' (length=7)
7 => string '008.cbf' (length=7)
8 => string '009.cbf' (length=7)
public 'S02' =>
array (size=3)
0 => string '001.sda' (length=7)
1 => string '002.sda' (length=7)
2 => string '003.sda' (length=7)
public 'S03' =>
array (size=2)
0 => string '001.klm' (length=7)
1 => string '002.klm' (length=7)
So you effectively have an array of arrays.
So for each "key" the associated "val" is an array that you have to loop through.
So you need to iterate through each key, then iterate through each val array.
foreach ($json as $key => $val) {
echo 'KEY IS: ' . $key;
echo '<br>';
foreach ($val as $value) {
echo 'VALUE IS: ' . $value;
echo '<br>';
}
echo '<br>';
}
The resulting output is...
KEY IS: S01
VALUE IS: 001.cbf
VALUE IS: 002.cbf
VALUE IS: 003.cbf
VALUE IS: 004.cbf
VALUE IS: 005.cbf
VALUE IS: 006.cbf
VALUE IS: 007.cbf
VALUE IS: 008.cbf
VALUE IS: 009.cbf
KEY IS: S02
VALUE IS: 001.sda
VALUE IS: 002.sda
VALUE IS: 003.sda
KEY IS: S03
VALUE IS: 001.klm
VALUE IS: 002.klmlm
VALUE IS: 002.klm

Related

How to match string to an Array to get the value?

I have an array with corresponding value.
Array
(
[0] => BBsma=200
[1] => SMAperiod=300
[2] => SMA1=400
[3] => SMA2=500
[4] => EMAperiod=300
[5] => EMA1=24
[6] => EMA2=8
)
Now I want to match a certain string like for example BBsma that should return 200. Any help?
Got the array using these codes.
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
array_shift($rows);
INDICATORS.txt content
BBperiod=100
BBsma=200
SMAperiod=300
SMA1=400
SMA2=500
EMAperiod=300
EMA1=24
EMA2=8
After you explode your text to the lines use this code:
for($i=0;$i<sizeof($rows);$i++)
{
$temp=explode("=",$rows[$i]);
if(sizeof($temp)==2)
{
$arr[$temp[0]]=$temp[1];
}
}
You will have named array in $arr
if you want to cast second part to int, you just change 6-line to this:
$arr[$temp[0]]=intval($temp[1]);
You could iterate over every line of your array and find the value with a regular match.
Code:
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
/*
$rows = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
*/
foreach ($rows as $k=>$v) {
if (preg_match("/(BBsma|SMAperiod|EMAperiod)=([0-9]+)/", $v, $matches)) {
echo "found value " . $matches[2] . " for entry " . $matches[1] . " in line " . $k . PHP_EOL;
}
}
Output:
found value 200 for entry BBsma in line 0
found value 300 for entry SMAperiod in line 1
found value 300 for entry EMAperiod in line 4
You can explode by new line as PHP_EOL like this
$col = "BBsma";
$val = "";
foreach(explode(PHP_EOL,$str) as $row){
$cols = explode("=",$row);
if(trim($cols[0]) == $col){
$val = $cols[1];
break;
}
}
echo "Value $col is : $val";
Live Demo
If your going to use the array a few times, it may be easier to read the file into an associative array in the first place...
$rows = [];
$file = "INDICATORS.txt";
$data = file($file, FILE_IGNORE_NEW_LINES);
foreach ( $data as $item ) {
$row = explode("=", $item);
$rows [$row[0]] = $row[1];
}
echo "EMA1 =".$rows['EMA1'];
This doesn't do the array_shift() but not sure why it's used, but easy to add back in.
This outputs...
EMA1 =24
I think that using array filter answers your question the best. It returns an array of strings with status code 200. If you wanted to have better control later on and sort / search through codes. I would recommend using array_walk to create some sort of multi dimensional array. Either solution will work.
<?php
$arr = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
$filtered = array_filter($arr,"filter");
function filter($element) {
return strpos($element,"=200");
}
var_dump($filtered); // Returns array with all matching =200 codes: BBSMA=200
Output:
array (size=1)
0 => string 'BBsma=200' (length=9)
Should you want to do more I would recommend doing something like this:
///////// WALK The array for better control / manipulation
$walked = [];
array_walk($arr, function($item, $key) use (&$walked) {
list($key,$value) = explode("=", $item);
$walked[$key] = $value;
});
var_dump($walked);
This is going to give you an array with the parameter as the key and status code as it's value. I originally posted array_map but quickly realized array walk was a cleaner solution.
array (size=7)
'BBsma' => string '200' (length=3)
'SMAperiod' => string '300' (length=3)
'SMA1' => string '400' (length=3)
'SMA2' => string '500' (length=3)
'EMAperiod' => string '300' (length=3)
'EMA1' => string '24' (length=2)
'EMA2' => string '8' (length=1)
Working with the array becomes a lot easier this way:
echo $walked['BBsma']; // 200
$anything = array("BBsma"=>"200", "SMAperiod"=>"300", "SMA1"=>"400");
echo "the value is " . $anything['BBsma'];
This will return 200

push array key and value in associative array

I want to push array into existing session array. I would like to use get[id] and I want to be able stack all the arrays added rather than delete them when a new array is pushed.
Bellow is my code and I am not getting the value, instead I get this error --- Array to string conversion. Thanks in advance.
**CODE
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals']=array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo $key;
echo $value;
}
?>
With your code, this is what $_SESSION looks like:
array (size=1)
'animals' =>
array (size=1)
0 =>
array (size=1)
'id' => string 'test' (length=4)
In your code :
foreach($_SESSION['animals'] as $key=>$value)
key will contain 0 and value will contain array('id' => 'test'). Since value is an array, you cannot echo it like this.
If you want to echo all the characteristics of each animal, this code will work :
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals'] = array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
// We go through each animal
foreach($_SESSION['animals'] as $key=>$animal)
{
echo 'Animal n°'.$key;
// Inside each animal, go through each attibute
foreach ($animal as $attribute => $value)
{
echo $attribute;
echo $value;
}
}

Check that variable is in an array

Possibly already been asked but I can't seem to find the answer I'm looking for.
How can I check that a variable is in an array?
Here is my code so far - ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
<?php if ($this->productOptions) { ?>
<?php foreach ($this->productOptions as $options) {
$array = $this->lastUpdatedProduct;
echo '<strong>' . $options['ProductID'] . '</strong>';
if(in_array($options['CentreID'], $array)) {
echo 'it exists';
}
}
}?>
Heres my array:
array
0 =>
array
'pid' => string '391' (length=3)
1 =>
array
'pid' => string '467' (length=3)
2 =>
array
'pid' => string '474' (length=3)
3 =>
array
'pid' => string '2985' (length=4)
4 =>
array
'pid' => string '2985' (length=4)
5 =>
array
'pid' => string '424' (length=3)
The problem is that $array is an array with arrays and you are trying to find something inside one of the inner arrays. Try with this:
foreach ($array as $entry) {
if (is_array($entry) && in_array($options['CentreID'], $entry))
echo 'it exists';
}
Ideally I wan't to echo out something when the ProductID is in the array
if(is_array($options['ProductID'])) { }
Live Preview
Edit
Ideally I wan't to echo out something when the ProductID also exists in the lastUpdatedProduct array as well as the productOptions array.
if(is_array($this->productOptions)) {
foreach($array as $pid) {
if(in_array($pid, $options['ProductID'])) {
//echo
}
}
}

How to extract array data in PHP variable with foreach?

I need to extract last array data i.e SiteName, Url, Title to the variable in php.
array
'ApplicableProductOfferings' =>
array
0 => string 'EasyDemo' (length=10)
'Artist' => string 'Hello' (length=10)
'ReferralDestinations' =>
array
0 =>
array
'SiteName' => string 'gettyimages' (length=11)
'Url' => string 'http://www.gettyimages.com/detail/160414706' (length=43)
'Title' => string 'Pixie Lott Launches The New BlackBerry Z10' (length=42)
'UrlComp' => string 'http://localhost.com' (length=197)
'UrlPreview' => string 'http://localhost.com' (length=164)
'UrlThumb' => string 'http://localhost.com' (length=82)
'UrlWatermarkComp' => string 'http://localhost.com' (length=197)
'UrlWatermarkPreview' => string 'http://localhost.com
try this.......
foreach($data as $dat)
{
foreach($dat['ReferralDestinations'] as $key => $d)
{
echo $d['SiteName'];
echo $d['Url'];
echo $d['Title'];
}
}
It depends on how you are storing the data in the array. If you have an array that already has the last array data, it's very simple.
foreach ($myArray as $var) {
echo $var;
}
or access individual elements as $myArray['SiteName'], $myArray['Url'] etc..
Assuming you have the above data in an array of arrays called $arrayOfArrays
foreach ($arrayOfArrays as $myArray) {
// $myArray now holds first array, second array etc as the loop is executed
// First time it holds 'ApplicableProductOfferings', second time 'ReferralDesinations'..
// If the array is 'ReferralDesitnations' you can loop through that array
// to get the elements you are looking for SiteName etc as below
foreach ($myArray as $URLElement) {
echo $URLElement;
}
}
$array1 = [];
$array2 = [];
foreach ($array1 as $key=> $val) {
extract($array2, EXTR_IF_EXISTS, $val);
}
// extract() flags => EXTR_IF_EXISTS ...
// http://php.net/manual/ru/function.extract.php

Different way to convert object to array using PHP

When use this code:
$array=(array)$yourObject;
The properties of $yourObject convert to index an array, but how can convert as one array, these means, the $yourObject be one index of $array and I echo $array[0] for access through object?!
Another way for question, please see this sample code:
<?php
$var1 = (string) 'a text';
$var2 = (array) array('foo', 'bar');
$var3 = (object) array("foo" => 1, "bar" => 2);
//It's OK.
foreach((array)$var1 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's OK.
foreach((array)$var2 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's NOT OK. I want through $var3 in output as an array with one index!
foreach((array)$var3 as $v) {
echo $v."<br>";
}
echo "<hr>";
?>
Other way:
I want use a variable in foreach but I not sure about type this, I want working foreach without error for any type variable (string, array, object,...)
For example I thinks must I have this sample output for some this types:
Output for $var1:
array
0 => string 'a text' (length=6)
Output for $var2:
array
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
Output for $var3:
array
0 =>
object(stdClass)[1]
public 'foo' => int 1
public 'bar' => int 2
And the end I sure the foreach return current result without error.
You mean to wrap your object inside an array?
$array = array($yourObject);
As mentioned by mc10, you can use the new short array syntax as of PHP 5.4:
$array = [$yourObject];

Categories