I have this API that returns this:
{"response":
[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}
I want to print all areas, but as an example above, Austin in Quebec has area value (Estrie), but Austin in Manitoba doesn't.
My code is:
for($i = 0; $i < count($json_array['response']); ++$i){
echo $json_array['response'][$i]['area'];
but the problem is I get this error Notice: Undefined index: area in... where area value is not present (like Austin in Manitoba).
How can I check is area is present or not?
There's two basic ways to can deal with this problem.
The simplest is to check the existence of the variable
echo array_key_exists('area', $json_array['response'][$i]) ? $json_array['response'][$i]['area'] : null;
The other way is to standardise the response from the API so that the area key always exists
function standardizeApi($values)
{
foreach ($values['response'] as $i => $details) {
if (!array_key_exists('area', $details)) {
$values['response'][$i]['area'] = null; // default value
}
}
return $values;
}
$json_array = standardizeApi($json_array);
// loop though as normal
The second way is better if you have more than one key to check. You can ensure the array contains values, even if the api is missing them.
Edit: Spelling
quick if
for($i = 0; $i < count($json_array['response']); ++$i){
if($json_array['response'][$i]['area']){
echo $json_array['response'][$i]['area'];
};
You can use the json decode as an object and get the item list:
$stringJson = '{"response":[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}';
$jsonObj = json_decode($stringJson);
foreach ($jsonObj->response as $item) {
echo $item->cid; // 5122405 5467453
}
Related
I want to get keys and values from a multi-dimensional array dynamically, to better explain what I'm trying to achieve please see the code below.
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $faq['faq1'][$i];
echo $faq['faq1_answer'][$i];
$i++;
}
The literal text above faq1 and faq1_answer needs to be replaced by the variable $q and $a respectively for me to be able to get the keys and values dynamically, but I cannot figure out how to add the variable.
The keys will always be the same, except for the number, which will change from 1 to 99. So with the code above, I can get the value of faq1 but I also need to grab the value of faq2 etc, hence why the variables above would work as I need.
tl;dr faq1 needs to be able to change to faq2 on the next iteration, hence the reason for me using $i.
Maybe like this?
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $f[$a];
echo $f[$a];
$i++;
}
How do I delete the whole line from an array? When the delete-button is pressed it should delete the whole line.
my array looks like that:
$liste[0][0] = email-user1
$liste[0][1]= password-user1
$liste[1][0] = email-user2
$liste[1][1]= password-user2
So if I delete the user one, the user2 should just take the place from user1(which should just disappear).
if (isset($_GET['delete'])){
$id=key($_GET['delete']);
for ($i = 0; $i < count($liste); $i++){
if ("$i"=="$id"){
unset($liste[$id][0]);
unset($liste[$id][1]);
unset($liste[$id][2]);
}
else{
}
}
update
I'm using array_splice($liste, $id, 1); now but everytime I try to save it to the file I get an error: implode(): Invalid arguments passed. For saving it to the file, I use the following function:
function saveDataToFile($fileName, $liste){
$file=fopen($fileName,"w");
for ($i = 0; $i < count($liste); $i++) {
$zArray=$liste[$i];
$zeile=implode("|", $zArray);
if(strlen($zeile) > 0){
$zeile=$zeile."\r\n";
fwrite($file, $zeile);
}
}
fclose($datei);
}
Try the below code:
$liste[0][0] = "email-user1";
$liste[0][1]= "password-user1";
$liste[1][0] = "email-user2";
$liste[1][1]= "password-user2";
$liste[2][0] = "email-user3";
$liste[2][1]= "password-user3";
unset($liste[1]); // say you want to delete this row
$new_arr = $liste;
unset($liste);
$i=0;
foreach($new_arr as $value){
$liste[$i] = $value;
$i++;
}
You can use array_splice() method:
array_splice($liste, $id, 1);
$liste[0][0], $liste[0][1] and $liste[0][2] are in real nothing else than a value array(value, value, value) (the inner array) which is assigned to $liste[0] (the outer array)
unsetting this (outer) array value $liste[0] is enough:
unset($liste[$id]);
If you care about the keys of this array (I see you loop from 0..n), you need to reindex your array using:
$liste = array_values($liste);
This will make your array behaving more like arrays normally do in other programming languages
Good practice is to use foreach instead of for. In this case you don't need to reindex:
for ($liste as $key=>$value){
if ("$key"=="$id"){
unset($liste[$key]);
}
But anyway you don't have to loop through an array just for finding a key. It's enough doing this:
if (isset($liste[$id])) { /* optional: check if the key exists */ }
unset($liste[$id]);
So I know how to error check an empty post value with an if empty combination, however how can this be done if the post data is an array and it needs to be applied to each value?
Example:
foreach (array($_POST['post_values']) as $test) {print_r($test); echo'<br />';};
where
<input name="post_values[value_1]">
<input name="post_values[value_2]"> etc.
I need to be able to say that if a value is not posted to any of the inputs, then that particular input = zero without applying a default value to the inputs themselves.
Therefore if value_1 = 5 and value_2 = blank, the array will show as 5 and 0.
Thanks in advance,
Dan
You can do something like this:
for ($i = 0; $i < count($_POST['post_values']); $i++){
if (empty($_POST['post_values'][$i])){
$_POST['post_values'][$i] = 0;
}
}
Would this work?
foreach ($_POST['post_values'] as $key=>$test) {
if($test==""){
$_POST["post_values"][$key]=0;
}
};
print_r($_POST['post_values']);
you can do the following. inside your look you can check for value
$value = (trim($test) != "" ? $test : 0);
echo $value; // if $test is blank then it would be 0 else would get value of $test.
I am using a $_COOKIE[array] in order to save data for a single input. This input will only submit if the user entered the same value twice. For instance, if they submitted apple, then orange, then banana, then apple, the form would submit on the second appearance of "apple".
I read [this tutorial](
http://phpprogramming.wordpress.com/2007/03/06/php-cookies-tutorial-and-examples/).
for ($i = 1; $i < 10; $i++) {
if (!isset($_COOKIE[$i])) {
setcookie("query" . [$i],$query,time()+604800,"/");
break1;
}
}
foreach ($_COOKIE["query"] as $key => $value) {
echo "$key:$value";
}
I believe it might be a syntax error since I get:
Warning: Invalid argument supplied for foreach()
If you know a better way (can't be mySQL), then please let me know!
$_COOKIE["query"] is not an array, that's whats producing the error.
$_COOKIE['query'] can not store an array. This is also why you get an error when you try to use it in the foreach. You could serialize your array before saving it though. Something like this
$array = array();
for ($i = 1; $i < 10; $i++) {
$array[] = $i;
}
setcookie("query",urlencode(serialize($array)),time()+604800,"/");
$query = unserialize(urldecode($_COOKIE['query']));
foreach ($query as $key => $value) {
echo "$key:$value";
}
also have a look at this post update cookie value in php for the expalanation why the urlencode / urldecode is used
I have a large array.
In this array I have got (among many other things) a list of products:
$data['product_name_0'] = '';
$data['product_desc_0'] = '';
$data['product_name_1'] = '';
$data['product_desc_1'] = '';
This array is provided by a third party (so I have no control over this).
It is not known how many products there will be in the array.
What would be a clean way to loop though all the products?
I don't want to use a foreach loop since it will also go through all the other items in the (large) array.
I cannot use a for loop cause I don't know (yet) how many products the array contains.
I can do a while loop:
$i = 0;
while(true) { // doing this feels wrong, although it WILL end at some time (if there are no other products)
if (!array_key_exists('product_name_'.$i, $data)) {
break;
}
// do stuff with the current product
$i++;
}
Is there a cleaner way of doing the above?
Doing a while(true) looks stupid to me or is there nothing wrong with this approach.
Or perhaps there is another approach?
Your method works, as long as the numeric portions are guaranteed to be sequential. If there's gaps, it'll miss anything that comes after the first gap.
You could use something like:
$names = preg_grep('/^product_name_\d+$/', array_keys($data));
which'll return all of the 'name' keys from your array. You'd extract the digit portion from the key name, and then can use that to refer to the 'desc' section as well.
foreach($names as $name_field) {
$id = substr($names, 12);
$name_val = $data["product_name_{$id}"];
$desc_val = $data["product_desc_{$id}"];
}
How about this
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// loop body
$i++;
}
I think you're close. Just put the test in the while condition.
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// do stuff with the current product
$i++;
}
You might also consider:
$i = 0;
while(isset($data['product_name_'.$i])) {
// do stuff with the current product
$i++;
}
isset is slightly faster than array_key_exists but does behave a little different, so may or may not work for you:
What's quicker and better to determine if an array key exists in PHP?
Difference between isset and array_key_exists