Frustration at trying to output two specific values from an Array - php

I am doing my head in trying to do a simple retrieval for specific arrays within a script so I have an original associative array:
$vNArray ['Brandon'] = $item[3];
$vNArray['Smith']= $item[4];
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];
Which outputs a common result for most values:
foreach ($vNArray as $key => $value){
if(!empty($value)){
$result .= "\t\t\t\t<li><strong>$key</strong>" .$value. "</li>\n";
}
But then I want two of these arrays to render differently so I added another script suggested by someone:
$display_id=array('Brandon', 'Murphy');
foreach ($vNArray as $key => $value){
if(!empty($value)){
//Looks into the display_id array and renders it differently
if (in_array($key, $display_id)) {
$result .= "\t\t\t\t<li id=\"$key\"><strong>$key</strong>$value</li>\n";
} else {
$result .= "\t\t\t\t<li><strong>$key</strong>$value</li>\n";
}
}
}
The problem is that i want the result for these arrays to contain both within the first result but when I tried to output
$result .= "\t\t\t\t$key[1]".$value[1]." \n";
PHP thinks that the index is the value's character index, so I'm having major syntax issues like id="/" r.
I have also tried
$result .= "\t\t\t\t<li id=\"". $display_id['Brandon']$value.\""><strong>$key[1]</strong>". $display_id['Murphy']$value." </li>\n";
But I am still getting wrong syntax issues...like
syntax error, unexpected T_VARIABLE
Or some other error like this.
Could someone please help?
EDITED
I have made the syntax corrections but I still need to specify the index:
The result from
result .= "\t\t\t\t<li id=\"". $display_id['Brandon'] . $value."\"><strong>" . $key[1] . "</strong>". $display_id['Murphy'] . $value." </li>\n";
Needs to be (Note how each value is on the same output depending on what I'm targeting):
<li id="Brandon Value"><strong>Brandon</strong> Murphy Value</li>
Right now it ignores the index value of . $display_id['Brandon'] . $value. or . $display_id['Murphy'] . $value." all together and just repeats:
<li id="Brandon Value"><strong>Brandon</strong> Brandon Value</li>
<li id="Murphy Value"><strong>Murphy</strong> Murphy Value</li>

Just do $key, forget the [1] bit. Same with $value.

Each value needs to be concatenated with another, so for example:
echo $a . $b . $c . $d . $e;
Notice the . contact that joins each variable with the the next / prev variable, so your line:
$display_id['Brandon']$value
should look like:
$display_id['Brandon'] . $value
^
I would do the following though.
$result .= sprintf('<li id="%s"><strong>%s</strong> %s</li>',$display_id['Brandon'] . $value,$key[1],$display_id['Murphy'] . $value);
Also using sprintf also make your code more readable.

Related

PHP: Creating an associative array programmatically

I have a return string from a 3rd party plugin that looks like a var_dump from an array. I'm trying to parse into a valid associative array. Looking at various examples and doing some tests with the code that follows. The last segment demonstrates the problem I'm having. I'm trying to parse out the data into a string and then programmatically create an array after my data string has been finished. When I do a print_r on $vegetables2, I get:
Array([0] => “Gourd”=”40 kilojoules”,”Artichoke”=”105 kilojoules”,”Cassava”=”550 kilojoules”)
And the echo $vegetables2["Artichoke"] produces no value. Can someone please guide me at the correct syntax to create the array equivalent to the first two examples?
//this works:
echo "From creating the entire array with a static string:<br/>";
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"] . "<br/>";
//this works too
$vegetables1['Gourd'] = "40 kilojoules";
$vegetables1['Artichoke'] = "105 kilojoules";
$vegetables1['Cassava'] = "550 kilojoules";
echo "From creating one element at a time:<br/>";
echo "Artichoke: " . $vegetables1["Artichoke"] . "<br/>";
//this doesn't work
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
echo $strData ."<br/>";
$vegetables2 = array($strData);
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
$dd=str_replace('"','',"$strData");
$ff=explode(',',$dd);
foreach ($ff as $c)
{
$xx=explode('=',$c);
$vegetables2["$xx[0]"]=$xx[1];
}
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
This string is your input:
"Array ( [Gourd] => 40 kilojoules [Artichoke] => 105 kilojoules [Casava] => 550 kilojoules )"
use strpos() to locate "("
use strpos() to locate ")"
use substr() to get what is between ( and )
use explode to divide the result wherever "[" appears
use array() to start a new array
use foreach to reformat each piece
use explode to divide each piece wherever "=>" appears
use trim to remove excess characters (left and right)
use $data[$key] = $value to create a new array to your liking

In PHP Trying to Get Array Foreach into XML

I Have an Array that I want a foreach to display the Key and Value as XML. The Page is coming up with <$value> and that is it? Any Ideas? Thank You!
$XML_a = array ("Ticket_ID" => "12343456");
$query = "";
$string_top =
"<varcor_api>
<response>";
foreach ($XML_a as $key => $value) {
$query .= "<" . $key . "><" . $value . "></" . $key . ">";
}
$string_bottom = "
</response>
</varcor_api>
";
echo $string_top . $query . $string_bottom;
It's bad idea to concatenate XML strings into XML structure. Instead, use Array to XML conversion algorithm - see Convert array to XML and How to convert array to SimpleXML.

php multidimensional array syntax

The code below has two commented-out variations on one line. They produce rather different results, as you'll see if run them - without the space between $array and [$key], the individual letters of the key are mapped out to the array values.
Can someone explain what's happening here and why?
Thanks!
<?php
$letters = array('A','B','C');
$numbers = array(1,2,3);
$matrix = array('Letter' => $letters, 'Number' => $numbers);
foreach($matrix as $array => $list)
{
echo '<ul>';
foreach($list as $key => $value)
// {echo "<li>$array [$key] = $value ";}
// {echo "<li>$array[$key] = $value ";}
echo '</ul>';
}
"$array[$key]" is interpreted as the array access (value of $array[$key]). Same as echo $array[$key];.
"$array [$key]" is interpreted as two different variables: $array and $key. Same as echo $array." [".$key."]";.
The reason for the difference in output is due to the way that PHP parses strings containing variables.
If you change:
{echo "<li>$array [$key] = $value ";}
to
{echo "<li>" . $array [$key] . " = $value ";}
It will result in the same thing and the line below it.
{echo "<li>$array[$key] = $value ";}
PHP is mostly whitespace agnostic, but not inside of strings where intrinsically whitespace matters.
remember that "double quotes" tries to execute your code, while "single quotes" deals your code as text only.
in this case:
echo "<li>$array[$key] = $value ";
this code is being evaluated. here is saying something like "put this value in this position of this array". in the other hand, this:
echo "<li>$array [$key] = $value ";
isn't being evaluated because, to php, doens't make sense to it's parser assign a value to something like this:
[$someting] = $value;
the above code returns a fatal error.
your code doesn't return a fatal error because php tries to handle your code in some way that doesn't throw an exception.
the last example of your code (the one with spaces) is the same as this:
echo '<li>' . $array . '[' . $key . '] = ' . $value;
in short: want to show some variable in some string? put the variables off the php string's interpretation:
echo $myvar . ' = ' . $myvalue;

Compare two array and get all differences

I have two arrays like this.
$array1=array(1,2,3,4,5,7);
$array2=array(1,2,3,4,5,6);
So, the output should bring the difference in both arrays.
The output should be.
1,2,3,4,5 -> These numbers exist in both arrays, so these should be ignored.
7 and 6 -> These numbers are the un-common in both arrays, so I need these values in array.
The output should be 7 & 6.
Help me out. I have tried array_diff and other array elements.
try this
array_merge(array_diff($array1,$array2),array_diff($array2,$array1))
foreach($array1 as $key => $value) {
if($value != $array2[$key]) {
echo "\$array1[" . $key . "] (" . $value . ") is different to \$array2[" . $key . "] (" . $array2[$key] . "<br />";
}
}

PHP elseif statement not executed even though initial if statement is false

I am writing a recursive function to print out the differences between 2 multildimensional php arrays. The purpose of this code is to see the difference between jpeg headers to deteremine how adobe bridge cs3 is saving rating information within the jpg file.
When I am single-stepping through the code using my eclipse - zend debugger ide, it appears that even though the initial if statement is false (ie neither values is an array), the subsequent elseif statements are never executed. The function is attached below.
Note: Changes since original post based on comments
Added a default level= ''
Removed comments between the if{} elseif{} blocks
Removed an else; at the end of the block that had no function
Encoded the < and > symbols so angle bracket would show in my code
function array_diff_multi($array1,$array2,$level=''){
$keys = array_keys($array1);
foreach($keys as $key)
{
$value1 = $array1[$key];
if(array_key_exists($key,$array2) ){
$value2 = $array2[$key];
if (is_array($value1) && is_array($value2)){ // Check if they are both arrays, if so recursion is needed
array_diff_multi($value1,$value2,$level . "[ " . $key . " ]");
}
elseif(is_array($value1) != is_array($value2)){ // Recursion is not needed, check if comparing an array to another type
print "<br>" . $level . $key ."=>" . $value1 . "as array, compared to ". $value2 ."<br>";
}
elseif($value1 != $value2){ // the values don't match, print difference
print "<br>" . $level . $key ."=>" . $value1 ." != " . $value2 ."<br>";
}
}
else{
print "<br>" . $level. $key . "does not exist in array2";
}
}
}
could it be because you have
else;
at the end...?
Try removing that or turning that into 'real code'
It works fine for me here. I put your function (with the tiny difference of adding a default value of '' to the level parameter), and these two arrays:
$a1 = array('foo', 'bar', 2, array('baz', '3', 4, array(54,45)));
$a2 = array('faz', 'bar', 4, array('buz', '3', 5, 54));
And got this output:
0=>foo != faz
2=>2 != 4
[ 3 ]0=>baz != buz
[ 3 ]2=>4 != 5
[ 3 ]3=>Arrayas array, compared to 54
Perhaps your starting arrays are not what you think they are...?
This doesn't exactly answer your question, but I think Adobe Bridge saves metadata in dotfiles in the same directory as the files. For example, sort information is saved in a .bridgesort file.
The only way that all the elseifs would be skipped is if the two variables are not arrays and are equal.

Categories