I have some json data, i want re-install it after match some condition.
$mm='a';
$nn='104';
$jn=array();
$j2='[
{"a":"c","n":"103","t":"rfg"},
{"a":"a","n":"104","t":"bmf"},// <- find the data, re-install from the next line
{"a":"b","n":"105","t":"tit"},
{"a":"a","n":"106","t":"iou"},
{"a":"b","n":"107","t":"wdf"}
]';
$t2=json_decode($j2);
foreach($t2 as $d2){
if($mm==$d2->a&&$nn==$d2->n){
continue;
}
$jn['a']=$d2->a;
$jn['n']=$d2->n;
$jn['t']=$d2->t;
$p.=json_encode($jn).',';
}
echo '['.substr($p,0,-1).']';
I need return json data as [{"a":"b","n":"105","t":"tit"},{"a":"a","n":"106","t":"iou"},{"a":"b","n":"107","t":"wdf"}]
I hope you understand that.
<?php
$mm='a';
$nn='104';
$jn=array();
$j2='[
{"a":"c","n":"103","t":"rfg"},
{"a":"a","n":"104","t":"bmf"},// <- find the data, re-install from the next line
{"a":"b","n":"105","t":"tit"},
{"a":"a","n":"106","t":"iou"},
{"a":"b","n":"107","t":"wdf"}
]';
$t2=json_decode($j2);
$i=0;
foreach($t2 as $d2)
{
if($mm==$d2->a && $nn==$d2->n)
{
$jn['a']=$d2->a;
$jn['n']=$d2->n;
$jn['t']=$d2->t;
if($i==1)
{
$p=json_encode($jn).',';
}
else
{
$p.=json_encode($jn).',';
}
}
$i++;
}
echo '['.substr($p,0,-1).']';
The following code will do the job
Append the string only after finding a match.
$mm='a';
$nn='104';
$jn=array();
$j2='[{"a":"c","n":"103","t":"rfg"},{"a":"a","n":"104","t":"bmf"},{"a":"b","n":"105","t":"tit"},{"a":"a","n":"106","t":"iou"},{"a":"b","n":"107","t":"wdf"}]';
$t2=json_decode($j2);
//echo "<pre>";
//print_r($t2);
//exit();
$append = false;
$p='';
foreach($t2 as $key=>$d2){
$jn['a']=$d2->a;
$jn['n']=$d2->n;
$jn['t']=$d2->t;
if($append){
$p.=json_encode($jn).',';
}
if($mm==$d2->a&&$nn==$d2->n){
$append=true;
}
}
echo '['.substr($p,0,-1).']';
Related
I'm trying to get a n else statement working with a print_r such that if there's no value it outputs "no values".
In the code I'm getting values from json converted to an array.
The logic I'm trying to achieve is
IF fieldTag contains "i" THEN output the content associated with it
ELSE says its empty.
Right now blank is outputted as opposed to "no values".
Thanks
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content']."<br>";
if(count($subfieldText2) > 0) {
print_r($subfieldText2);
} else {
echo "no values";
}
}
}
count() is for arrays, not strings, the way to get the length of a string is with strlen(). And if you want to check for an empty string, just compare it with $var == "", you don't need to get the length.
But you're concatenating "<br>" to the value, so the length will never be zero. You could check the length before concatenating.
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
if($subfieldText2 != "") {
$subfieldText2 .= "<br>";
print_r($subfieldText2);
} else {
echo "no values";
}
And to avoid having to repeat that long expression to access the field, you could use foreach
for($res['entries'][$i]['bib']['varFields'] as $field) {
if ($field['fieldTag'] == "i") {
$subfieldText2 = $field['subfields'][0]['content'];
...
}
}
this worked for me thanks everyone
$subfieldText2="not detected";
echo "ISBN: ";
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
echo $subfieldText2.", ";
}
}
echo $subfieldText2;
I'm running if statements to identify each variable independently. My code is a bit messy and long but it works with no problem. I'd like to see if it is possible to use an array to store them and run a loop to see if there is a match, instead of using if statements.
PHP code...
if (move_uploaded_file($_FILES["index_deslizador_Cfile1"]["tmp_name"], $index_deslC1)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Cfile2"]["tmp_name"], $index_deslC2)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Cfile3"]["tmp_name"], $index_deslC3)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Cfile4"]["tmp_name"], $index_deslC4)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile1"]["tmp_name"], $index_deslM1)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile2"]["tmp_name"], $index_deslM2)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile3"]["tmp_name"], $index_deslM3)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile4"]["tmp_name"], $index_deslM4)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else {
echo "Sorry, there was an error uploading your file.";
}
I'm fairly new to PHP, so I may get scolded for this suggestion :)
If you could get $index_deslC# variables into an array, you might be able to do something like this:
$i = 1
$destination = array($index_deslC...
foreach($_FILES["index_deslizador_Mfile" . $i]["tmp_name"] as $filename) {
isset(move_uploaded_file($filename, $destination[$i]) ?
echo "<script>window.open('../index.php','_self')</script>" : echo '';
$i++;
}
So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";
I'm really unsure how to describe this, so please forgive me.
Basically, I'm reading from an XML, and then generating an IF statement that checks all records in the XML and if a condition matches, details about that record is displayed.
What I want to add, is a similar function but in reverse, but outside the foreach loop, so it's only displayed once.
foreach($xml as $Reader) { $items[] = $Reader; }
$items= array_filter($items, function($Reader) use ($exclude) {
if($Reader->Picture == 'None' || in_array($Reader->Pin, $exclude)) {
return false;
}
return true;
});
usort ($items, function($a, $b) {
return strcmp($a->Status,$b->Status);
});
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
}
}
if (!$items) { echo "Please check back in a moment when our readers will be available!"; }
So, in the XML file each Reader has a Status that can be one of three values: Available, Busy or Logged Off.
So what I'm doing, is for each record in the XML, checking if the Reader status is available.. and if so, echo the above line.
But I want to add in, that if NONE of the readers show as 'Available' to echo a single line that says 'Please check back in a moment'.
With the code above, ifthere are four readers online, but they're all busy.. nothing is displayed.
Any ideas?
Just use a simple boolean value
$noneAvailable = true;
foreach($items as $Reader) {
if($Reader->Status == 'Available' && !in_array($Reader->Pin, $exclude)) {
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$noneAvailable = false;
}
}
if ($noneAvailable) {
echo "Please check back in a moment";
}
I managed to take the answer given above, and combine it with XPath to just filter the records in the XML based on the status given using xPath.
include TEMPLATEPATH."/extras/get-readers.php";
$readers = $xml->xpath('/ReaderDetails/Reader[Status="Available"]');
$gotOps = false;
foreach ($readers as $Reader)
{
echo "<a href='/details?Pin=".$Reader->Pin."'>".$Reader->Name ." (".$Reader->Pin.")</a> is available! ... ";
$gotOps = true;
}
if ($gotOps!=true)
{
echo 'Please check back in a moment when our readers will be available!';
}
my questions:
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result = array_search("你",$state);echo $result;
}else
{
echo "No Exists";
}
i expect the result of "1", however the output is "No Exists", i don't know why the program can't get the value of the key "你".
array_search will search the given array by value. Try the following:
$state = array("你"=>1);
if(array_key_exists("你", $state)) {
echo $state["你"];
} else {
echo "No Exists";
}
// => 1
» demo
Hope below function will help.
<?php
$array = array('arr1'=>array('find_me'=>'yes you did.'));
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
echo get_value_by_key($array,'find_me');
?>
the encoding type of the show paper and the store paper is GB2312.
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result1 = $state["你"];
echo $result1; // can get the value 111
}else
{
echo "No Exists";
}
the code above can be executed rightly. i can't show my problems accurately. Now i paste out my code , there is some questions.
<?php
$file = file("GB2312-HanZiBianMa.txt"); // file encoding type ANSI
foreach ($file as $line_num => $line)
{
list($no,$hex,$dec) = preg_split('[\t]',htmlspecialchars($line));;
$result[$hex] = $dec;
}
$result_2 = array_flip($result);
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
foreach($result_2 as $k=>$each) //can get the value using the preg_match
{
if(preg_match('/你/', $k))
echo $k."\t".$each."<br/>";
}
?>
the format of GB2312-HanZiBianMa.txt is as follows:
1947 c4e3 你
1948 c4e4 匿
1949 c4e5 腻
1950 c4e6 逆
if your want to test the code , you can save the php code and save the GB2312.. file.
the question is:
why can't the following function get the right value ? the data comes from file and one stores together.
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}