PHP Multiple Arrays [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the following example array:
Array
(
[0] => Array
(
[artist] => Artist43141
)
[1] => Array
(
[artist] => Artist2313
)
[2] => Array
(
[artist] => ArtistAdsa
)
[3] => Array
(
[artist] => ArtistAadas
)
)
How do I turn it into something like: "Artist43141, Artist2313, ArtistAdsa, ArtistAadas"
I'd like to know because as far as I tried with some similar questions already answered I wasn't able to find out how.

I would say something like this would work just fine:
$newArray = array_map(function($a) {return $a['artist'];},$oldArray);
No need for loops, or anything so complicated.

You want to create a space separated string containing only the values of the array.
To do so, try:
<?php
$array = Array
(
array(
'artist' => 'Artist43141'
),
array(
'artist' => 'Artist2313'
),
array(
'artist' => 'ArtistAdsa'
),
array(
'artist' => 'ArtistAadas'
),
);
$str = implode(' ', array_map(function($a){ return current($a); }, $array));
Check the PHP Manual for current() and array_map() to learn more about what the above example is doing.
Happy coding!
EDIT:
According to your comment:
I have one more issue, one of my artist values has a special character 'é', and now it doesn't print them. Where should I apply the htmlspecialchars() (if that's supposed to apply)?
…I want to add the following to this answer:
Modify the above code example like this to handle character encoding (assuming you're using UTF-8 encoding):
$str = implode(' ', array_map(function($a)
{
return htmlentities(current($a));
}, $array));
In case you're not using utf8 yet, start doing so by adding this to your php codes which echo to the browser:
header('Content-Type: text/html; charset=utf-8');
or the following in the header section of your html files:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8" />
...
So read up on PHP's htmlentities() and utf8 encoding.
Have fun.

Related

convert array into two different string php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an array with following elements:
$arr = array(
'nick' => "blabla",
'pass => "blabla2"'
);
I would like to convert it somehow to strings, the first string would be the value of nick - "blabla", the second string would be the value of pass - "blabla2"
Thank you.
If you want to convert elements of the array to separate string variables you can use extract function to import elements from an array to variables. For example:
$arr = array(
'nick' => "blabla",
'pass' => "blabla2"
);
extract($arr);
echo $nick, ' ', $pass;
$arr = [
'nick' => "blabla",
'pass' => "blabla2"
];
$string_one=$arr['nick'];
$string_two=$arr['pass'];

Include a php-file with multiple arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm having a problem with a simple include statement and I have no idea what's causing it.
First I'm storing information about tables and columns in a file called dbInit.php
which looks like this:
<?php
$aTableNames = array (
"tbl_crs" => "tbl_crs",
"tbl_lct" => "tbl_lct",
"tbl_prf" => "tbl_prf",
"tbl_qst" => "tbl_qst",
"tbl_uni" => "tbl_uni",
"tbl_usr" => "tbl_usr"
);
$aAuxTableNames = array (
"aux_crs_lct" => "aux_crs_lct",
"aux_lct_prf" => "aux_lct_prf",
"aux_uni_crs" => "aux_uni_crs"
);
?>
Now I simply want to access these arrays from another file. So I included it like this:
include "Ini/dbInit.php";
So far so good. Now I want to use the values of the arrays like this:
$sTable1 = $aAuxTableNames["aux_uni_crs"];
$sTable2 = $aTableNames["tbl_crs"];
The directory looks like this:
How can I access these arrays in the way sown above?
Thanks so much in advance.
Best regards
Amnney
I had no issue implementing this. So basically This is what I did. I copied your structure by having an include file with the arrays, exactly as you have posted here. Then I created a test file on the root of my server. This test file was php as well and I did the include as normal. Created the new variables, and then print_r(''); the 2 new variables you created out and received no errors.
This is my dbinit.php file:
<?php
$aTableNames = array (
"tbl_crs" => "tbl_crs",
"tbl_lct" => "tbl_lct",
"tbl_prf" => "tbl_prf",
"tbl_qst" => "tbl_qst",
"tbl_uni" => "tbl_uni",
"tbl_usr" => "tbl_usr"
);
$aAuxTableNames = array (
"aux_crs_lct" => "aux_crs_lct",
"aux_lct_prf" => "aux_lct_prf",
"aux_uni_crs" => "aux_uni_crs"
);
?>
Ok so exactly as yours is. Then I created my file on the root called testpage.php:
<?php
include('inc/dbinit.php');
$sTable1 = $aAuxTableNames["aux_uni_crs"];
$sTable2 = $aTableNames["tbl_crs"];
print_r($sTable1);
print_r($sTable2);
?>
My structure as indicated: Structure
Absolutely no issues running this or retrieving the data. Hope this helps.
Final Output: Final Output
Try this:
// Ini/dbInit.php
<?php
return array(
'aTableNames' => array(
"tbl_crs" => "tbl_crs",
"tbl_lct" => "tbl_lct",
"tbl_prf" => "tbl_prf",
"tbl_qst" => "tbl_qst",
"tbl_uni" => "tbl_uni",
"tbl_usr" => "tbl_usr"
),
'aAuxTableNames' => array(
"aux_crs_lct" => "aux_crs_lct",
"aux_lct_prf" => "aux_lct_prf",
"aux_uni_crs" => "aux_uni_crs"
),
);
In file, where you want to get Ini/dbInit.php
<?php
$config = include "Ini/dbInit.php";
$sTable1 = $config['aAuxTableNames']['aux_uni_crs']
$sTable2 = $config['aTableNames']['tbl_crs'];

Way to apply HTML code to each element of php array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm building a gallery application and I've been having Issues finding out If there Is a way I can put HTML around each PHP array value In my case images,
I believe that If I echo It I'll get the values as text. I don't want to echo the values as text any options?
Thanks in advance.
If I understand correctly the following may be of some help, If you want to display the images in HTML you could use something like the following.
$images = array(
"1" => "image1.png",
"2" => "image2.jpeg",
"3" => "image3.gif"
);
foreach ($images as $key => $image) {
echo "<img src=\"{$image}\" alt=\"image {$key}\"/>";
}
and if you want to place the images inside HTML and back into your array you can use the following.
$images = array(
"1" => "image1.png",
"2" => "image2.jpeg",
"3" => "image3.gif"
);
foreach ($images as $key => $val) {
$images[$key] = "<img src=\"{$val}\" alt=\"image {$key}\"/>";
}
Not sure if this is just a "coders block", but it's very simple. grab the array, iterate it, wrap the output of each array element in a div and echo it back to the requesting page.
foreach($array as $item):
echo '<div>', $item ,'</div>';
endforeach;
Option 1
You seem to be looking for array_walk:
bool array_walk(array &$Input, callable $Fn [, mixed $extra = null ])
Applies the user-defined function Fn to
each element of the array Input, optionally
passing it the user-specified object $extra.
This is an example of wrapping every element of the array between two user-specified values.
<?php
$arry = array(
'pear',
'orange',
'banana',
);
array_walk($arry, function(&$item, $key, $data) {
$item = $data['before'].$item.$data['after'];
}, array(
'before' => 'this is a ',
'after' => ' squash.',
));
print_r($arry);
?>
Output:
Array
(
[0] => this is a pear squash.
[1] => this is a orange squash.
[2] => this is a banana squash.
)
Option 2
Another option could be that of using preg_replace_callback to perform a bulk replace on each element. This allows greater flexibility both in specifying what to replace, and how to replace it:
<?php
$arry = array(
'pear squash',
'squishy orange',
'squoshed banana',
);
// FIRST - wrap everything in double round brackets
$arry = preg_replace_callback('/^.*$/', function($matches){
return "(($matches[0]))";
}, $arry);
// SECOND - convert anything like "SQUASH" (but with whatever letter instead
// of the "A" - to "juice":
$arry = preg_replace_callback('/(.*)squ(.)sh(.*)/', function($matches){
// $matches[2] contains the whatever letter.
return $matches[1].'juice'.$matches[3];
}, $arry);
print_r($arry);
returns now
Array
(
[0] => ((pear juice))
[1] => ((juicey orange))
[2] => ((juiceed banana))
)

Sort PHP Numerically & Identify which is closest to date [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got an array for events on my site that looks like this:
array(
'title' => 'Name',
'link' => 'http://www.eventssite.com',
'image' => '_img/event_img.jpg',
'location' => 'Florida, US',
'year' => '2013',
'date' => 'Dec. 12-14',
'desc' => 'Description about the event.',
'dateid' => '1212013'
),
I'd like to sort the array before the foreach by the dateid so that they show in the proper Date order.
Additionally I'm trying to identify which one of the events is closest to the actual date, as I am using a carousel type system that needs to know which to display first.
I've researched usort and am not able to get it to go on my own, Thank you for any assistance on these!
Using this function: http://php.net/usort
An example would be something like:
<?php
//just an array of arrays with the date as one of the values of the array
$array = array(
array(
'date' => '05/02/1988',
'name' => 'Jacob'
),
array(
'date' => '12/12/1968',
'name' => 'Sherry'
),
array(
'date' => '05/15/1978',
'name' => 'Dave'
)
);
//usort is used for non conventional sorting.
//which could help in this case
//NOTICE - we are not setting a variable here!
//so dont call it like $array = usort(...) you will just be setting $array = true
usort($array,'sortFunction');
//display the results
var_dump($array);
//function called by usort
function sortFunction($a,$b){
//turn the dates into integers to compare them
//
$strA = strtotime($a['date']);
$strB = strtotime($b['date']);
//don't worry about sorting if they are equal
if($strA == $strB){
return 0;
}
else{
//if a is smaller than b, the move it up by one.
return $strA < $strB ? -1 : 1;
}
}
?>
(in case youre interested, line 40 is called a Ternary)
edited for clarity

Understanding variable assignment in a foreach loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a pretty basic question:
What is this statement actually doing (specifically the =>$p)?
foreach ($email->parts as $partno=>$p) {
I understand the the basics but the =>$p is not clear
In a foreach loop you can ask for both the key and value to be returned
$array = array('cat' => 'Tom', 'mouse' => 'Jerry');
foreach($array as $animal => $name) {
echo $name . ' is a ' . $animal . '<br>';
}
So the loop will output
Tom is a cat
Jerry is a mouse
This synthax is to assign the array key name or object property name to the variable $partno and it's value to $p.
This way you can do for instance $email->parts[$partno] = $p;.
It can be particularly useful if you have parallel arrays with different information bound by the key, so you need this information to obtain related data from the other array when iterating one of them.
For instance:
$person = array(
1 => 'Santa Claus',
2 => 'Homer Simpson',
3 => 'Papa Smurf'
);
$location = array(
1 => 'North Pole',
2 => 'Springfield',
3 => 'Smurf village'
);
foreach ($person as $id => $name)
echo "$name live in {$location[$id]}\n";
$partno is the key, $p is value
e.g. $email->parts = array("key" => "value");
Read this
http://www.php.net/manual/en/control-structures.foreach.php

Categories