Conditional statement in an json encoded array - php

I'm showing a "Review Your Order:" part of a page with the success callback of a json_encode array. I probably said that completely wrong in technical terms but hopefully you can see what I'm trying to do.
Part of the PHP processing page...
$results = array(
'roomname' => $_POST['roomX'],
'qty' => $_POST['qtyX'],
and I want the results to be returned as...
Room Name: Whatever is returned. (notice the label "Room Name: ")
But I only want the label to show IF the POST has a value assigned.
Example of how I think it should look but it's not working..
$results = array(
'roomname' => if (!$_POST['roomX']=='' { echo 'Room Name: ' .$_POST['roomX'];},
Does that make sense? There are dozens of options for each order and I don't want "Label: " in front of a bunch of values that are empty.
EDIT: Added code from answer below.
// beginning of array
$results = array(
'roomname' => $_POST['roomX'],
'qty' => $_POST['qtyX'],
// more code...
// end of array.. remember not to have a comma on this last one.
);
// pasted answer between the array ending and the json_encode line.
if ($_POST['roomX'] != ''){
$results['roomname'] = "Room Name: ".$_POST['roomX'];
}
$json = json_encode($results);
echo $json;

here is one way, you can user a Ternary operation
$results = array(
'roomname' => $_POST['roomX']==''? 'Room Name: '.$_POST['roomX']: '',
);
this will add a blank string if the value is empty
the other way will be to just add the value later;
$results = array(...);
if ($_POST['roomX'] != ''){
$results['roomname'] = $_POST['roomX']
}

$results = array();
if (isset($_POST['roomX'])) {
$results[] = array(...);
}
if there's no post value, you just end up with an empty array.

you can make an if statement before assigning any data to roomname like so
$result = array(
'roomname' => ($_POST['roomX'] !== '')? 'Room name: '.$_POST['roomX']:''
);
The thing I used here is a shortend if statement and works as following: (if statement)? true : false;
I hope this will help you.

Related

Insert the content of an array in a database in php

I wrote this function that scrapes some content from a web page to my database. My issue is with my array variable $lang, everything works as I want when I test with print_r($lang), but I am unable to insert the values in my DB because it looks like the array is empty when I used it in the second foreach.
Please guys, how can insert $lang in my DB properly? Here below is my code. Your help will be much appreciated. Thank you!
<?php
$html = file_get_html($url);
$links = array();
$lang = array();
foreach ($html->find('div.blockshadow h1') as $i => $title) {
$textValue = $title->plaintext;
if (strpos($textValue, 'VF') !== false) {
$lang[] = 'VF';
} elseif (strpos($textValue, 'VOSTFR') !== false) {
$lang[] = 'VOSTFR';
} elseif (strpos($textValue, 'VO') !== false) {
$lang[] = 'VO';
}
}
foreach ($html->find('div.blockshadow iframe') as $key => $a) {
$linkUrl = $a->src;
$wpdb->insert(
$table_name, array(
'Idioma' => $lang,
'Calidad' => ucwords("HDRIP"),
'Enlace' => $linkUrl,
'PID' => $return['ID'],
'Tipo' => '3',
)
);
}
If you do not plan to split up your data into multiple tables and want to keep it all in one column, you can use json_encode/serialize.
Which one of both you choose is pretty much up to you, but stay consistent.
When you read out your data, just use json_decode/unserialize and you get back your initial array.
Something like:
$data = json_encode([
'Idioma' => $lang,
'Calidad' => ucwords("HDRIP"),
'Enlace' => $linkUrl,
'PID' => $return['ID'],
'Tipo' => '3',
]);
$wpdb->insert($table_name, $data);
And for reading, you first want to select the data from your table like normal, but before using it, you have to json_decode/unserialize the column which yields this data.
Convert the array into string, using the implode function and also do check if the value is empty or not, something like this.
$newLang = "";
if(!empty($lang))
{
$newLang = implode(',',$lang);
}
And use the $newLang variable for the database, also inside the foreach loop you want to insert all the values present in the array, then use the above way, if you want specific values with each loop, then use $newLang[$key] .
Hope this helps.
PS: You can't insert array directly into table.

Adding String to Value in PHP Array

I have an HTML form which collects values in a format needed for a certain task. After completing the task, I would like to perform an additional task using the same values from the form without having the user enter the information in a second time.
The problem that I am running into is that the second task requires two of the fields to be formatted differently when they are sent to their destination.
Here is the array on the second script that is being sent where the keys on the left are being assigned the values on the right by the values from the form.
$contactFields = array(
// field name in myServer => field name as specified in html form
'aaaaaaaa' => 'email',
'bbbbbbbb' => 'stuff',
'cccccccc' => 'morestuff',
'dddddddd' => 'blah',
'eeeeeeee' => 'blahh',
'ffffffff' => 'blahh',
'gggggggg' => 'tobacco', //tobacco use
'hhhhhhhh' => 'amount', //face amount
);
What I am trying to do is add the string ',000' to the value of 'amount' taken from the user input. Again, I cannot just change the value on the HTML form because I need the value formatted differently for the first script.
I have tried
'hhhhhhhh' => 'amount'.',000',
No bueno. I also tried a similar method before the array, but to no avail.
For the field receiving the value of 'tobacco', I am trying to convert it from a 0 or 1 value, to a yes or no value. I tried this
if ($tobacco == 1) {
$tobacco = "yes";
} else if ($tobacco == 0) {
$tobacco = "no";
} else {
$tobacco = "?";
};
But that just caused the script to return a null value.
$Tobacco was originally assigned above the contactFields array as such
//
Assigns variables to input fields
$aaaaaaaa = $_POST['email'];
$bbbbbbbb = $_POST['aaaaaaaa'];
$cccccccc = $_POST['bbbbbbbb'];
$dddddddd = $_POST['cccccccc'];
$eeeeeeee = $_POST['dddddddd'];
$ffffffff = $_POST['eeeeeeee'];
$gggggggg = $_POST['tobacco'];
$hhhhhhhh = $_POST['amount'];
Any suggestions? Thanks. PHP is not my strongpoint.
If you want to change the value of the array item you can do it this way:
$contactFields['hhhhhhhh'] = $contactFields['hhhhhhhh'].",000";
echo $contactFields['hhhhhhhh'];
// outputs
// amount,000
$contactFields['gggggggg'] = ($contactFields['gggggggg'] == '1' ? 'yes' : 'no');
echo $contactFields['gggggggg'];
// outputs
// yes
or you can set variables if you don't want to alter your array:
$newAmmount = $contactFields['hhhhhhhh'].",000";
echo $newAmount;
// outputs
// amount,000
$newTobacco = ($contactFields['gggggggg'] == '1' ? 'yes' : 'no');
echo $newTobacco;
// outputs
// yes
But as was mentioned, if 'amount' is truly a number, use number functions and don't store it as a string.

Access array where key is a variable

$furtherKeys = "['book']['title']";
echo $this->json['parent'] . $furtherKeys;
This breaks. Is there anyway to do something like this?
I know you could explode $furtherKeys, count it, and setup a loop to achieve this, but I'm just curious if there is a direct way to concatenate an array with key names stored in a variable and have it work.
I want to use it for populating input field values from a json file. If I set a data-variable for each input field like:
<input type="text" data-keys="['book']['title']">
I could get the value of the data-variable, then just slap it onto the json object, and populate the value.
Thanks!
You can simply parse your build up array access using eval(). See my exaple here:
$example = array(
'foo' => array(
'hello' => array(
'world' => '!',
'earth' => '?'
)
),
'bar' => array());
// your code goes here
$yourVar = null;
$access = "['foo']['hello']['world']";
$actualAccesEvalCode = '$yourVar = $example'.$access.';';
eval($actualAccesEvalCode);
echo 'YourVal now is '.$yourVar;
Yet, i think it is better to use iteration. If $this->json['parent'] actually is an array, you write a recursive function to give you the result of the key.
See this ideone work here:
<?php
$example = array(
'foo' => array(
'hello' => array(
'world' => '!',
'earth' => '?'
)
),
'bar' => array());
function getArrayValueByKeyString($array,$keystring) {
$dotPosition = stripos ($keystring , '.' );
if($dotPosition !== FALSE) {
$currentKeyPart = substr($keystring, 0, $dotPosition);
$remainingKeyPart = substr($keystring, $dotPosition+1);
if(array_key_exists($currentKeyPart, $array)) {
return getArrayValueByKeyString(
$array[$currentKeyPart],
$remainingKeyPart);
}
else {
// Handle Error
}
}
elseif (array_key_exists($keystring, $array)) {
return $array[$keystring];
}
else {
// handle error
}
}
echo '<hr/>Value found: ' . getArrayValueByKeyString($example,'foo.hello.world');
Although I don't know how to do this with both book and title at the same time, it is possible to use variables as key names using curly braces.
// SET UP AN ARRAY
$json = array('parent' => array('book' => array('title' => 'The Most Dangerous Game')));
// DEFINE FURTHER KEYS
$furtherKeys1 = "book";
$furtherKeys2 = "title";
// USE CURLY BRACES TO INSERT VARIABLES AS KEY NAMES INTO YOUR PRINT STATEMENT
print "The Parent Book Title Is: ".$json['parent']{$furtherKeys1}{$furtherKeys2};
This outputs:
The Parent Book Title Is: The Most Dangerous Game

Can we store brackets into a PHP variable to get the value of array?

I want to store square bracket string in a variable so that I can use that variable to get the value of array. How can I do that?
Example:
$vehicle = array("car"=>"volvo","bike"=>"polygon");
$bracket1="['car']";
$bracket2="['bike']";
echo $vehicle.$bracket1;//my expected result = 'volvo';
echo $vehicle.$bracket2;//my expected result = 'polygon';
Case
Suppose I have this data
$data = array(
"vehicles"=>array(
array(
"name"=>"volvo",
"manufacturer"=>"abc",
"color"=>array("blue"=>"wonderful","red"=>"fantastic")),
array(
"name"=>"toyota",
"manufacturer"=>"def",
"color"=>array("blue"=>"awesome","red"=>"good")),
array(
"name"=>"mecedes",
"manufacturer"=>"ghi",
"color"=>array("blue"=>"nice","red"=>"great","green"=>"good","brown"=>"elegant")),
));
$fields = array(
"$data['vehicles']['name']",
"$data['vehicles']['manufacturer']",
"$data['vehicles']['color']['blue']",
"$data['vehicles']['color']['red']"
);
//a function to print those data according to user parameter($fields, it may uncertain pattern)
function get_data($data,$fields){
for($c=0;$c<count($data);$c++){
foreach($fields as $field){ //field to show
echo $field;
}
}
}
edited:
$data = array(
"vehicles"=>array(
array(
"name"=>"volvo",
"manufacturer"=>"abc",
"color"=>array("blue"=>"wonderful","red"=>"fantastic")),
array(
"name"=>"toyota",
"manufacturer"=>"def",
"color"=>array("blue"=>"awesome","red"=>"good")),
array(
"name"=>"mecedes",
"manufacturer"=>"ghi",
"color"=>array("blue"=>"nice","red"=>"great","green"=>"good","brown"=>"elegant")),
));
$c=0;
$fields = array( // note added zeros here... these are your "vehicle" array key
"{$data['vehicles'][$c]['name']}",
"{$data['vehicles'][$c]['manufacturer']}",
"{$data['vehicles'][$c]['color']['blue']}",
"{$data['vehicles'][$c]['color']['red']}"
);
for($c=0;$c<count($data['vehicles']);$c++){
foreach($fields as $field) {
echo $field . PHP_EOL;
}
}
//the output print : volvo abc wonderful fantastic volvo abc wonderful fantastic volvo abc wonderful fantastic
//the output expectetd : volvo abc wonderful fantastic toyota dev awesome good mercedes ghi nice great
Why don't you try this:
$vehicle = array("car" => "volvo", "bike" => "polygon");
$bracket1 = "car";
$bracket2 = "bike";
echo $vehicle[$bracket1]; //my expected result = 'volvo';
echo $vehicle[$bracket2]; //my expected result = 'polygon';
Edit: you want a function that does this... You don't need it. This is a basic PHP language construct.
Anywho, here's your function (wrapping that basic PHP language construct up in an extra layer) - I'll even throw in a basic error check (return false if the array key doesn't exist):
function searchMyHugeArrayForSomething($huge_array, $something) {
if(!array_key_exists($something, $huge_array))
return false; // return false if array key doesn't exist
return $huge_array[$something]; // return your desired result......
}
Demo:
$my_huge_array = array(
'pet' => 'cat',
'wife' => 'sarah',
'brother' => 'john'
// etc
);
echo searchMyHugeArrayForSomething($my_huge_array, 'wife'); // sarah
echo searchMyHugeArrayForSomething($my_huge_array, 'husband'); // returns false (oop, sexist!)
echo searchMyHugeArrayForSomething($my_huge_array, 'brother'); // john
// etc............?
Make sense?
Edit: OK, multidimensional array is very different (your original question was flat). You are having an issue here because you're missing a level in between vehicles and name, etc. There's an array there containing numeric indexes, so your path would actually be $data['vehicles'][0]['name'] - and when that's the case, you can basically just echo each line of your array to get the value of the array key parsed into a string.
In this example I've added both curly braces to each line to parse as a variable variable, and because your example won't actually run as it is (it's trying to parse the array keys as a variable and syntactically failing), and added the zero array key. You'll need to work out which array key you want to target yourself, this is just using the first:
$fields = array( // note added zeros here... these are your "vehicle" array key
"{$data['vehicles'][0]['name']}",
"{$data['vehicles'][0]['manufacturer']}",
"{$data['vehicles'][0]['color']['blue']}",
"{$data['vehicles'][0]['color']['red']}"
);
foreach($fields as $field) {
echo $field . PHP_EOL;
}
Output:
volvo
abc
wonderful
fantastic

PHP Variable Variable inside []'s

Thanks for the help below, however, I'm still having some problems, I'll try and explain further:
I have a variable as follows:
$value['questions'];
Now, I need to do a check in a loop, so I have this piece of code in the loop:
if($results[$value['questions']]==4){blah blah blah};
but the problem I am having is that the value of $value['questions'] is q1 but I need the q1 to be a string (i.e. inside quotes '') in the $results section of the code, so the $results element should look like this...
if($results['q1']==4){blah blah blah};
currently it looks like this
if($results[q1]==4){blah blah blah};
Make sense?
Thanks again for the help.
Hi all,
I hope there is a simple solution!
I have a variable:
$results['q1'];
Is it possible to have the 'q1' element as a variable, something like this:
$results['$i[question]'];
Have not been able to find a solution on Google and researching the PHP manuals...
Anyone got a suggestion/ solution?
Thanks,
Homer.
Yes, it is possible to use a variable as indice, when accessing an array element.
As an example, consider this portion of code :
$results = array(
'a' => 'sentence a',
'b' => 'hello !',
);
$indice = 'a';
echo $results[$indice];
Which will give the following output :
sentence a
Here, $indice is a quite simple variable, but you could have used whatever you wanted between the [ and ], like, for instance :
functions : $results[ my_function($parameter) ]
array element : $result[ $my_array['indice'] ]
Which seems to be what you want to do ?
object property : $result[ $obj->data ]
...
Basically, you can use pretty much whatever you want there -- as long as it evaluates to a scalar value (i.e. a single integer, string)
In your specific case, you could have $results declared a bit like this :
$results = array(
'q1' => 'first question',
'q2' => 'second question',
);
And $i would be declared this way :
$i = array(
'question' => 'q1'
);
Which means that $i['question'] would be 'q1', and that the following portion of code :
echo $results[ $i['question'] ];
Would get you this output :
first question
Edit : To answer the specific words you used in the title of your question, you could also use what's called variable variable in PHP :
$variable = 'a';
$indice = 'variable';
echo $results[ $$indice ];
Here :
$indice is 'variable'
and $$indice is 'a'
which means you'll get the same output as before
And, of course, don't forget to read the Arrays section of the PHP manual.
The Why is $foo[bar] wrong? paragraph could be of interest, especially, considering the example you firt posted.
Edit after the edit of the OP :
If $value['questions'] is 'q1', then, the two following portions of code :
if($results[$value['questions']]==4){blah blah blah}
and
if($results['q1']==4){blah blah blah}
should do exactly the same thing : with $results[$value['questions']], the $value['questions'] part will be evaluated (to 'q1') before the rest of the expression, and that one will be the same as $results['q1'].
As an example, the following portion of code :
$results = array(
'q1' => 4,
'q2' => 6,
);
$value = array('questions' => 'q1');
if($results[$value['questions']]==4) {
echo "4";
}
Outputs 4.
You can do:
$results[$i['question']];
This will first access the array $i to get the value corresponding to the key 'question'. That value will be used as the key into the array $results.
Your way: $results['$i[question]'];
is actually trying to get the value corresponding to the key '$i[question]' in the array $results. Since the key is in single quote, variable interpolation does not happen and the entire string is treated literally.
Alternatively you can also do:
$results["$i[question]"]; // using double quotes also works.
Example:
$arr1 = array('php' => 'zend', 'java' => 'oracle');
$arr2 = array('p' => 'php', 'j' => 'java');
echo $arr1[$arr2['p']]; // prints zend.
echo $arr1["$arr2[p]"]; // prints zend.
<?php
$result['q1'];
// is equivalent to
$index = 'q1';
$result[ $index ];
Now $index can be as complex as you want it to be. For example something like this is also possible:
$result[ 'q' . round( $someArray[$i] / 2 ) ];
CODE
<?php
$results = array(
'q1' => 'This is a result called q1.',
'q2' => 'So, can you access this?',
'$i[question]' => 'This is a result called $i[question]',
);
$i = array(
'question' => 'q2',
'answer' => 'Yes.'
);
echo '<pre>';
echo $results['q1'] . "\n"; // Using Array's is easy -
echo $results['$i[question]'] . "\n"; // all you gotta do is make sure
echo $results[$i['question']] . "\n"; // that you understand how
echo $i['answer']; // the keys work.
?>
OUTPUT
This is a result called q1.
This is a result called $i[question]
So, can you access this?
Yes.

Categories