I'm having a hard time checking for empty values in my associative array. And if a value is empty/null replace it with the wording "not entered"
My $_SESSION['gift'] array:
Array
(
[0] => Array
(
[giftGiveMy] => 1a
[giftTo] => 2a
)
[1] => Array
(
[giftGiveMy] => 1b
[giftTo] => '' //### empty ###
)
)
if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach( $_SESSION['gift'] as $value) {
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $value['giftTo'] .".\n";
}
$gifts = join($gifts);
}
The above outputs:
I give my 1a to 2a.
I give my 1b to .
I would like it read:
I give my 1a to 2a.
I give my 1b to not entered.
You can replace all empty and NULL value with not entered with the help of array_walk_recursive and use you code as it is
array_walk_recursive($arrayMain, 'not_entered');
function not_entered(& $item, $key) {
if (($item === "") || ($item ==NULL)){
$item = "not entered";
}
}
var_dump($arrayMain);
Just use foreach to loop all values and check if it's empty
$emptyText = '<b>not entered</b>';
// `empty` will also be true if element does not exist
if (empty($_SESSION['gift'])) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach($_SESSION['gift'] as $value) {
$myGive = !empty($value['giftGiveMy']) ? $value['giftGiveMy'] : $emptyText;
$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : $emptyText;
$gifts[] = "I give my {$myGive} to {$giftTo}.";
}
$gifts = implode("\r\n", $gifts); // Or `<br/>` if outputted to HTML
}
You should modify your code and write it this way:
if (!isset($_SESSION['gift']) || empty($_SESSION['gift'])) {
$gifts = "No specific gifts identified.\n";
} else {
foreach( $_SESSION['gift'] as $value) {
$gift_to = !empty($value['giftTo']) ? $value['giftTo'] : '<strong>Not entered<strong>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $gift_to .".\n";
}
}
You might want to try this:
if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach( $_SESSION['gift'] as $value) {
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". (!empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>') .".\n";
}
$gifts = join($gifts);
}
If you would like to make it a little cleaner you could extract the ternary operator into something like this;
$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $giftTo .".\n";
Try:
$arr = $_SESSION['gift'];
foreach($arr as $key => $array) {
if($array['giftGiveMy'] == null || empty($array['giftGiveMy'])) {
$arr[$key]['giftGiveMy'] = 'not entered.';
}
if($array['giftTo'] == null || empty($array['giftTo'])) {
$arr[$key]['giftTo'] = 'not entered.';
}
}
I'd write that this way:
$gifts = "No specific gifts identified.\n";
$filter = function($str) {
return empty($str) ? 'not entered' : $str;
};
if(!empty($_SESSION['gift'])) {
$gifts = '';
array_walk($_SESSION['gift'], function($given) use(&$gifts,$filter){
$gifts .= 'I give my ' . $filter($given['giftGiveMy']) . ' to ' . $filter($given['giftTo']) . ".\n";
});
}
You can use for the below code also there is no need any extra Php functions.
$arr = array(
0 => array(
'giftGiveMy' => '1a',
'giftTo' => '2a'
),
1 => array(
'giftGiveMy' => '1b',
'giftTo' => ''
)
);
$str = '';
if (!empty($arr)) {
foreach ($arr as $key => $value) {
if ($value['giftGiveMy'] == '')
$value['giftGiveMy'] = 'not entered';
if ($value['giftTo'] == '')
$value['giftTo'] = '<strong>not entered</strong>';
//$new[$key] = $value;
$str .= "I give my " . $value['giftGiveMy'] . " to " . $value['giftTo'] . "<br />";
}
}else {
$str = 'No specific gifts identified.<br />';
}
echo $str;
This validates an associative array with empty() (see array_filter), but may not respond to the original question.
<?php
$var = array();
$var['position'] = 'executive';
$var['email'] = 'a#email.com';
$var['message'] = 'This is the message';
$var['name'] = 'John Doe';
$var['telephone'] = '123456789';
$var['notneededparam'] = 'Nothing';
$expectedParams = ['position', 'email', 'message', 'name', 'telephone'];
$params = array_intersect_key($var, array_flip($expectedParams));
// check existence of keys and that they are valid
if(count($params) != count($expectedParams) || count(array_filter($params)) != count($expectedParams)){
echo "not valid\n";
die();
}
extract($params);
var_dump($name);
Other functions used here: array_flip(), array_intersect_key(), count(), extract(), var_dump(),
Related
I have a foreach loop for array $students where I am trying to compare a paramater $find that I get from a form to $students array's $key value -> if they match it checks if the student is enrolled (this works) and if not it should print "Not found" but it doesn't do anything.. I have tried a lots of things but nothing works, please help!
I translated this from finnish so there might be typo's but the problem is in the syntax..
//values come from a file
$students[$key] = array('key' => $key, 'name' => $name, 'occ' => $occ);
foreach ($students as $value) {
//This doesn't work - $find comes from a form
if ($value["key"] != $find) {
$phase= "Not found";
$enroll= "";
//echo "$phase $enroll";
continue;
}
//This works
elseif ($value["key"] == $find) {
$phase= $value["name"] . "(" . $value["key"] . "):";
if ($value["occ"] == "1") {
$enroll= " yes";
continue;
}
elseif ($value["occ"] == "0") {
$enroll= "no";
continue;
}
}
//It prints out for example "John(1234): yes"
//But nothing if the studentnumber = key doesn't match..
echo "$phase $enroll";
}
You don't need to check $value["key"] twice
$students[$key] = array('key' => $key, 'name' => $name, 'occ' => $occ);
foreach ( $students as $value ) {
$phase= "Not found";
$enroll= "";
if ( $value["key"] == $find ) {
$phase= $value["name"] . "(" . $value["key"] . "):";
$enroll = ( $value["occ"] == "1" ) ? " yes" : "no";
}
echo "$phase $enroll";
}
I have written a code, that finds value in second array if it finds specific key from first array, but my question is - is it possible to do it better? for example without 3 loops ?
For example here are keys and values to search for, which user has checked at form and submitted ($tegoszukamy):
array (
'kolor' =>
array (
0 => 'bialy',
1 => 'zielony',
),
'rozmiar' =>
array (
0 => '60',
1 => '70',
),
'rozdzielczość' =>
array (
0 => '1200x1800',
),
'moc' =>
array (
0 => '500W',
),
);
Here is array with products IDs where searching is performed ($tuszukamy):
array (
47 =>
array (
'rozmiar' => '50,60,70,80,90,100',
'kolor' => 'bialy,czarny',
),
48 =>
array (
'rozmiar' => 'L,M,XS,S,L',
'kolor' => 'zielony,niebieski,czerwony,zolty,bialy,czarny',
),
49 =>
array (
'rozdzielczość' => '1200x1800',
'prędkość' => '60str/min',
)
)
Here is my code that is working fine:
foreach ($tegoszukamy as $atrybut=>$wartosci_szukane) {
foreach ($tuszukamy as $numer_posta=>$wartosci_zbioru ) {
if (array_key_exists($atrybut, $wartosci_zbioru) !== FALSE){
foreach ($wartosci_szukane as $ws) {
if (strpos($wartosci_zbioru[$atrybut],$ws) !== FALSE) {
echo
'We have found'
.$ws.
'in'
.$wartosci_zbioru[$atrybut].
'where product id is'
.$numer_posta.
''
;}
else {
echo
'We found not'
.$ws.
'in'
.$wartosci_zbioru[$atrybut].
''
;}
}
}
}
}
Is it possible to do it better/with better code performance/speed, because I dont know if these 3 loops will be good when user filters through eg. 10000 products.
I came up with the following alternatives:
1.
class Subject {
private $attr_name;
private $attr_values;
function __construct($attr_name, $attr_values) {
$this->attr_name = $attr_name;
$this->attr_values = $attr_values;
}
public function check($key, $item) {
$found = array();
if (isset($item[$this->attr_name])) {
foreach($this->attr_values as $val) {
strstr($item[$this->attr_name], $val) && array_push($found, $val);
}
}
count($found) > 0 ?
$message = "Found attribute <u>" . $this->attr_name . "</u> with value <b>" . implode(", ", $found) . "</b> in ID: " . $key . "."
:
$message = "No matches for <u>" . $this->attr_name . "</u> found in ID: " . $key;
return $message;
}
}
foreach ($tegoszukamy as $attr_name=>$attr_values) {
$filtered = array_map(array(new Subject($attr_name, $attr_values), "check"), array_keys($tuszukamy), $tuszukamy);
foreach($filtered as $result) {
echo $result . '<br>';
}
}
2.
foreach ($tegoszukamy as $attr_name=>$attr_values) {
$filtered = array_filter($tuszukamy, function ($item, $key) use($attr_name, $attr_values) {
$found = array();
if (isset($item[$attr_name])) {
// var_dump($item[$attr_name]);
foreach($attr_values as $val) {
strstr($item[$attr_name], $val) && array_push($found, $val);
}
}
count($found) > 0 ?
$message = "Found attribute <u>" . $attr_name . "</u> with value <b>" . implode(", ", $found) . "</b> in ID: " . $key . "."
:
$message = "No matches for <u>" . $attr_name . "</u> found in ID: " . $key;
echo $message . "<br>";
return count($found) > 0;
}, ARRAY_FILTER_USE_BOTH);
// something to do with $filtered;
}
I'm not sure whether either of them is faster than yours. I'll leave the testing to you. :)
The first one was inspired by jensgram's answer to this question: PHP array_filter with arguments
I am getting the result from web service SOAP client. I have created an array to get the result and display it using json format. I am getting few of my results properly. I have SerialEquipment parameter which is array and i need to get the result using foreach loop. I am doing an mistake there. I dont know how can i assign my $vehiclResult array in this for each statement. So that all the results at last i will collect and display using json using vehicleResult array.My mistake is in the foreach loop.
structure for SerialEquipment parameters:
Code:
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$vehiclResult = array(
'WE_Number' => $vehicle['WE Number'] ."<br>",
'Vehicle Type'=> $vehicle['Vehicle Type'] . "<br>",
'HSN' => $vehicle['HSN'] . "<br>",
'TSN' => $vehicle['TSN'] . "<br>"
);
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['SerialEquipment'] = $key. "<br>";
$vehiclResult[$key]['Code'] = $obj->Code. "<br>";
$vehiclResult[$key]['Desc Short'] = $obj->Desc_Short. "<br>";
$vehiclResult[$key]['Desc Long'] = $obj->Desc_Long. "<br>";
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc). "<br>";
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc). "<br>";
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
}
You need to check if your array have the key so:
if(!isset($vehiclResult[$key]))
if not, you need to create it:
$vehiclResult[$key] = array(); // as an array
Also, you don't really need to make a description of your "item". You can Parse your JSON on the result page to output some text.
You can do something like.
Do something like:
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['serial'] = $key;
$vehiclResult[$key]['code'] = $obj->Code;
$vehiclResult[$key]['short_desc'] = $obj->Desc_Short;
$vehiclResult[$key]['long_desc'] = $obj->Desc_Long;
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2;
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode;
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc;
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode;
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc);
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode;
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc);
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
If you would keep your "text" and your <br> code, do the samething but add what you want to output after the "="
EDIT
** A HAVE CHANGE THE CODE PREVIOUSLY..
if you want to test your $vehiclResult, try something like:
foreach($vehiclResult as $key=>$value){
if(!is_array($value))
var_dump($value);
else {
foreach($value as $key2=>$value2){
if(!is_array($value2))
var_dump($value2);
else {
foreach($value2 as $key3=>$value3){
var_dump($value3);
}
}
}
}
I have problem with search in arrays , in 2 arrays , the first array have one structure fixed and the second send the vars from url and can have some values empty , for example
FIRST ARRAY :
The structure it's this :
id value , cat value , subcat value and country value
$ar_val="134567,dogs,food,EEUU";
The second var get from URL
$ar_url="134567,dogs,toys,EEUU";
As you can see in the second var , $ar_url i have one value no same to the first structure of $ar_val in this case toys
I want get compare the fixed structure of $ar_val and get if true or false if have same value in the same order from $ar_val
I try this :
$ar_val="134567,dogs,food,EEUU";
$ar_url="134567,dogs,toys,EEUU";
$exp_ar_val=explode(",",$ar_val);
$exp_ar_url=explode(",",$ar_url);
foreach ($exp_ar_val as $exp_ar_val2)
{
$ar_val_end[]=$exp_ar_val2;
}
foreach ($exp_ar_url as $exp_ar_url2)
{
$ar_val_end2[]=$exp_ar_url2;
}
$end_results=array_intersect($ar_val_end,$ar_val_end2);
With this I want know for example: If I search by id and for example for cat , get result positive in 2 arrays i have the same data , but if search for subcat i can´t get results because are differents in one have food and in other have toys , but with array_intersect no get this for compare
Thank´s , Regards
I think he wants to check if a value exists in either array. try this...
<?
function inarray($value,$array=array()){
if(in_array($value,$array)){
return true;
}else{
return false;
}
}
$ar_val=array("134567","dogs","food","EEUU");
$ar_url=array("134567","dogs","toys","EEUU");
$a = inarray("food",$ar_val);
$b = inarray("food",$ar_url);
if($a!=false and $b!=false)
echo "Found in both arrays";
elseif($a==true and $b==false)
echo "Found in first array";
elseif($a==false and $b==true)
echo "Found in second array";
else
echo "Not Found in any array";
?>
Try this:
$ar_val="134567,dogs,food,EEUU";
$ar_url="134567,dogs,toys,EEUU";
$arrayVal = explode(',', $ar_val);
$arrayUrl = explode(',', $ar_url);
$maxLength = max(sizeof($arrayVal), sizeof($arrayUrl));
$arrayIdsEqual = array();
$arrayIdsDifferent = array();
for ($i = 0; $i < $maxLength; $i++) {
if (isset($arrayVal[$i]) && isset($arrayUrl[$i])) {
if ($arrayVal[$i] == $arrayUrl[$i]) {
$arrayIdsEqual[] = $i;
}
else {
$arrayIdsDifferent[] = $i;
}
}
else {
//you arrive here if you have 2 arrays that don't have the same size / sme number of variables
}
}
//assuming your 2 arrays ALWAYS have the same size, you can use the following logic
if (empty($arrayIdsDifferent)) {
echo '2 arrays are the same';
}
else {
echo "Differences: \n";
foreach ($arrayIdsDifferent as $indexDifferent => $currentIdDifferent) {
$output = 'difference ' . ($indexDifferent + 1) . ': ';
$output .= 'val = ' . $arrayVal[$currentIdDifferent];
$output .= '; ';
$output .= 'url = ' . $arrayUrl[$currentIdDifferent];
echo $output;
echo "\n";
}
}
You can see this working here: http://3v4l.org/pTQns
You can use array_diff for this, which is perfect for comparison purposes:
<?php
$ar_val= array ("0" => "134567", "1" => "dogs", "2" => "food", "3" => "EEUU");
$ar_url= array ("0" => "134567", "1" => "dogs", "2" => "EEUU", "3" => "food");
$result = array_diff($ar_val, $ar_url);
$num = 0;
if ($result != NULL) {
echo "unique array keys: TRUE" . "\n\n";
print_r($result);
echo "\n\n";
} else {
echo "unique array keys: FALSE" . "\n\n";
}
foreach($ar_val as $key) {
if ($ar_val[$num] != $ar_url[$num]) {
echo "intersecting array key different: TRUE" . "\n> ";
print_r($ar_val[$num]);
echo "\n\n";
}
$num++;
}
?>
Just compare them with equal without any complicated operations.
$ar_val = "134567,dogs,food,EEUU";
$ar_url = "134567,dogs,toys,EEUU";
$exp_ar_val = explode(",", $ar_val);
$exp_ar_url = explode(",", $ar_url);
var_dump($exp_ar_val == $exp_ar_url); // false, elements does not match
$exp_ar_url = $exp_ar_val;
var_dump($exp_ar_val == $exp_ar_url); // true, all elements match
shuffle($exp_ar_url);
var_dump($exp_ar_val == $exp_ar_url); // false, different order
Hi i have this code to output a array list
$Sql1 = "SELECT * FROM tabmp3
WHERE Mp3_Player = 1
";
$Query1 = mysql_query($Sql1, $Conn)or die(mysql_error($Conn));
$musicas = array();
while($Rs1 = mysql_fetch_array($Query1)){
$musicas[] = array( title => $Rs1['Musica_Nome'], autor => "Grupo Fronteiras", mp3 => "http://site/Musicas/".$Rs1["Disco_Id"]."/".$Rs1["Musica_Mp3"] );
}
echo ( json_encode($musicas) );
this output
[{"title":"Alegria do Pov\u00e3o","autor":"Grupo Fronteiras","mp3":"http:\/\/site\/Musicas\/3\/201302140204413c390efdb9957eebd8d85c262f2a4929.mp3"}, {"title":"Bem na moda da fronteira","autor":"Grupo Fronteiras","mp3":"http:\/\/site\/Musicas\/2\/20130214032235fabd12471ffc7790c9204f891919bca8.mp3"}]
i need to remove double quotes from keys and fix the http link to looks like this
[{title:"Alegria do Pov\u00e3o",autor:"Grupo Fronteiras",mp3:"http://site/Musicas/3/201302140204413c390efdb9957eebd8d85c262f2a4929.mp3"},{title:"Bem na moda da fronteira",autor:"Grupo Fronteiras",mp3:"http://site/Musicas/2/20130214032235fabd12471ffc7790c9204f891919bca8.mp3"}]
Thanks
Try this..I know it is not very good way to do it.. I am writing this to show you that you have to make the form that you wanted in your php code only.
$json = json_encode($musicas);
$json = preg_replace('/["]/', '' ,$json);
$json = str_replace(':',':"', $json);
$json = str_replace(',','",',$json);
$json = str_replace('}]','"}]',$json);
echo $json;
By this way you will acheive what you wanted. But please find something good way to do it.
The correct answer should be this, as commented by #AlvaroLouzada
$json = json_encode($musicas);
$json = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $json);
echo $json ;
I looked a lot for an elegant solution to fix this issue without doing changing things over javascript or just replace quotes via preg_replace (for the case that the values would contain quotes) and end up doing it by myself. even if it's too late, I hope it would help those who are looking for the same solution.
function json_encode_advanced(array $arr, $sequential_keys = false, $quotes = false, $beautiful_json = false) {
$output = "{";
$count = 0;
foreach ($arr as $key => $value) {
if ( isAssoc($arr) || (!isAssoc($arr) && $sequential_keys == true ) ) {
$output .= ($quotes ? '"' : '') . $key . ($quotes ? '"' : '') . ' : ';
}
if (is_array($value)) {
$output .= json_encode_advanced($value, $sequential_keys, $quotes, $beautiful_json);
} else if (is_bool($value)) {
$output .= ($value ? 'true' : 'false');
} else if (is_numeric($value)) {
$output .= $value;
} else {
$output .= ($quotes || $beautiful_json ? '"' : '') . $value . ($quotes || $beautiful_json ? '"' : '');
}
if (++$count < count($arr)) {
$output .= ', ';
}
}
$output .= "}";
return $output;
}
function isAssoc(array $arr) {
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
usage:
$array = [
'someField' => '"value"', // double quotes for string if needed
'labelField' => '"label"', // double quotes for string if needed
'boolean' => false,
'numeric' => 5,
'render' => [
'option' => 'function() {
console.log("Hello World!");
console.log(\'Hello World!\');
}',
],
];
echo json_encode_advanced($array);
result:
{
someField : "value",
labelField : "label",
boolean : false,
numeric : 5,
render : {
option : function() {
console.log("Hello World!");
console.log('Hello World!');
}
}
}
Instead of doing echo ( json_encode($musicas) );, do something like this:
$json_string = json_encode($musicas);
$json_string = str_replace('\/', '/', $json_string);
echo $json_string;