$fidimp = implode('"', $fidarr);
$friendsimp = implode('<a href="../profile?id=', $funamearr);
$impglue = '</a><br />' . $fidimp . '>';
echo('<a href="../profile?id=' . $fidimp . '>' . implode('</a><br />', $funamearr));
This is the code I'm working with.
$funamearr has 2 values in it: "Conner" and "Rach667"
$fidarr has 2 values in it as well: "2" and "3" (the user's id's)
When this code is run, it only makes "Conner" a link (it works, by the way) How can I make it so that "Rach667" shows up as a link too?
First build an associative array from your ids to your names, then create an array of links and implode it, something like:
<?php
$funamearr = array( "Conner", "Rach667" );
$fidarr = array( 2, 3 );
$users = array_combine($fidarr, $funamearr);
foreach($users as $id => $name) {
$links[] = sprintf('%s', $id, $name);
}
echo implode('<br/>', $links);
Well I don't recommend using implode in this case but as said by LokiSinclair to use a loop.
<?php
foreach($funamearr as $key => $value) {
echo '' . $value . '<br/>";
}
This case assumes that the array keys of $funamearr and $fidarr match with eachother.
Outside the code I would make two tips.
1 Use usefull variable names.
$funamearr is not telling me much, except the arr part because it probably is an array. I would recommand $usernames (multiple so array ;)
2 Keep data together
No we have to hope that the keys are the same. but if you keep the data at the same level we won't and ofter easier in use
ie
array(
array(
'id' => 1,
'name' => 'test',
),
array(
'id' => 2,
'name' => 'test_name_2',
),
)
Related
I have two arrays which I wish to combine so that name and value can be side by side.
I have this code:
$mgl = array(
'200101',
'200201',
'200202'
);
$mpro = array(
'Current Account',
'Regular Saving Account',
'Ileya Target'
);
array_push($response, array(
"glno"=>$mgl,
"product"=>$mpro
));
echo json_encode(array("server_response"=> $response));
When I viewed it it appeared this way:
{"server_response":[{"glno":["200101","200201","200202"],"product":["Current
Account","Regular Saving Account","Ileya Target"]}]}
I want it in this format
{"server_response":[
{"glno":"104100","product":"Micro Loans"},
{"glno":"200101","product":"Current Account"},
{"glno":"200201","product":"Regular Saving Account"}
]}
It's easy enough using a foreach loop, using the first array as the start point and (as long as the arrays are the same length) just pick out the same value from the second array...
$response = [];
foreach ( $mgl as $key => $value ) {
$response[] = ["glno" => $value, "product" => $mpro[$key]];
}
echo json_encode(array("server_response"=> $response));
gives..
{"server_response":[{"glno":"200101","product":"Current Account"},
{"glno":"200201","product":"Regular Saving Account"},
{"glno":"200202","product":"Ileya Target"}]}
You could use array_combine(), this would be one solution of many in PHP.
<?php
$mgl=array("Micro Loans","Current Account","Ileya Target");
$mpro=array("104100","200101","200201");
$c=array_combine($mgl,$mpro);
print_r($c);
?>
This is my array:
$customer_info=[
array(
'name'=>array(
'fistname'=>'jason',
'lastname'=>'jason'
),
'id'=>'1'
),
array(
'name'=>'name2',
'id'=>'1'
)
];
and I want to get firstname and lastname from this array .
array_column($customer_info, 'name') should give you an array of all 'name' elements in your 2d array. I'll edit the answer if you can explain better what you want to do here.
If you really want to do it with a foreach loop, simply:
$output = [];
foreach ($customer_info as $row) {
$output[] = $row['name']
}
Should be fairly straight-forward, but we are looping through your array, checking if 'name' is an array or a string, and handling both scenarios.
This will display the information on the page, I wasn't sure if this is what you wanted or if you wanted to store the information into an array for use later.
If you want this stored as an array, what is the format of the array you need, are you going to concatenate the first and last names or store them in a multi-dimensional array?
foreach($customer_info as $key => $customer) {
if(is_array($customer['name'])) {
echo 'First Name: ' . $customer['name']['firstname'] . '.<br />';
echo 'Last Name: ' . $customer['name']['lastname'] . '.<br />';
} else {
echo 'Name is: ' . $customer['name'] . '.<br />';
}
}
this should work fine:
for first array:
$name = $customer_info[0]['name']['fistname'];
$family = $customer_info[0]['name']['fistname'];
for second array:
$name = $customer_info[1]['name'];
$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
Say I have custom fields with the keys p_title_1 p_value_1 p_title_2 p_value_2
Each of these has values within them and I would like to loop through p_title_[i] and p_value_[i] and show them on the page so that title and value would be grouped together in their own div.
I can't seem to figure out how to write it as a loop to show the 1's together and 2's together.
Reason it needs to be in a loop is incase more custom fields get added in the future. At current I have the following but it only echos the key and value
<?php
$custom_fields = get_post_custom( get_the_ID() );
$my_custom_field = $custom_fields['p_title_1'];
foreach ( $my_custom_field as $key => $value )
echo $key . " => " . $value . "<br />";
?>
Help is appreciated
Use the field name to build an array.
Where the array looks like:
array
1 =>
array
'title' => 'title 1'
'value' => 'value 1'
Loop through your fields and add to the array:
You can get the array index using explode function
$parts = explode ( '_' , $fieldname );
$name = $parts[0];
$index = $parts[1];
And add the value to the array:
$array[$index][$name] = $value;
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.