PHP Multidimensional Arrays - php

I'm trying to make a universal script that adds keywords to my individual pages (since header is in an include file) so I am getting the end of the url (multi.php) and retrieving the desc etc. from it's array. For some reason instead of returning keywords or descriptions it instead just returns "m" . . . it's kind of random and has me scratching my head. Here's what I got
<html>
<head>
<title>Multi-Demensional Array</title>
<?php
$path = pathinfo($_SERVER['PHP_SELF']);
$allyourbase = $path['basename'];
$pages = array
(
"multi.php" => array
(
"keywords" => "index, home, test, etc",
"desc" => "This is the INDEX page",
"style" => "index.css"
),
"header.php" => array
(
"keywords" => "showcase, movies, vidya, etc",
"desc" => "SHOWCASE page is where we view vidya.",
"style" => "showcase.css"
)
);
?>
</head>
<body>
<?php
foreach($pages as $key => $value)
{
if($key == $allyourbase)
{
echo $key['desc'];
}
}
?>
</body>
</html>

The reason why this is happening is because in PHP if I had the following code:
$hello = 'world';
and I attempted to do the following:
echo $hello[0];
PHP Would treat the string as an array and return me whatever is in position 0, which would result in w, when your using a foreach your asking PHP to set the key of the array to $key, and it's value to $value.
you then echo echo $key['desc'];, as the value is a string, php sees it as an integer based index, so it will ignore your call for desc and then return the first index, if you were to change echo $key['desc'] to echo $value['desc'] which is a hash based array it will return the desired results.
You should just be able to do this:
if(isset($pages[$allyourbase]))
{
echo $pages[$allyourbase]['desc'];
}
No need for the loop

try
echo $key['desc'];
replace with
echo $value['desc'];

Other people have provided some great solutions, but it's important that you understand exactly what is happening here, so you don't make the same mistake again. Pay careful attention to the comments, and you will be on your way to successful coding!
Here's what is happening:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
// At this point: $key = 'multi.php'
// Also: $value = array( ... );
// Keep in mind: $key['desc'] = $key[0] = 'm';
// You are grabbing the first letter of the 'multi.php' string.
// When dealing with strings, PHP sees $key['desc'] as $key[0],
// which is another way to grab the very first character of 'multi.php'
echo $key['desc'];
// You really want $pages[$key]['desc'], but below
// is a better way to do it, without the overhead of
// the loop.
}
}
If you kept the loop, which is really unnecessary, it would look like this:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
echo $value['desc'];
}
}
The best solution is to replace the loop with the following code:
if (isset($pages[$allyourbase])) {
echo $pages[$allyourbase]['desc'];
} else {
// error handling
}

If I'm reading this right, echo $key['desc']; should be echo $value['desc'];.

Related

PHP dynamic array name with loop

I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}

how to get the index of an array using the value in php

<?php
$interests[50] = array('fav_beverages' => "beer");
?>
now i need the index (i.e. 50 or whatever the index may be) from the value beer.
I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.
please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.
thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer");
$interests[50] = array('fav_cuisine' => "arabic");
$interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.
This should work in your case.
$interests[50] = array('fav_beverages' => "beer");
function multi_array_search($needle, $interests){
foreach($interests as $interest){
if (array_search($needle, $interest)){
return array_search($interest, $interests);
break;
}
}
}
echo multi_array_search("beer", $interests);
If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:
$needle = 'beer';
foreach ($interests as $index => $arr) {
foreach ($arr as $value) {
if ($value == $needle) {
echo $index;
break;
}
}
}
Demo

print_r statement doesn't seem to work

I am building a web crawler. It finds all the links on a page and their titles and meta descriptions etc. It does that fine. Then i wrote an array which gives all the starting urls for the links I want. So if it crawls a link and its url begins with any value in the array which gives the starting urls, insert into $news_stories.
The only problem is it doesn't seem to be inserting into them. The page returns blank and now it says that the array_intersect statement wants an array and that I havent specfied an array which I have.
In summary, I am struggling to understand where my code doesn't work and why the wanted urls aren't being inserted.
$bbc_values = array(
'http://www.bbc.co.uk/news/health-',
'http://www.bbc.co.uk/news/politics-',
'http://www.bbc.co.uk/news/uk-',
'http://www.bbc.co.uk/news/technology-',
'http://www.bbc.co.uk/news/england-',
'http://www.bbc.co.uk/news/northern_ireland-',
'http://www.bbc.co.uk/news/scotland-',
'http://www.bbc.co.uk/news/wales-',
'http://www.bbc.co.uk/news/business-',
'http://www.bbc.co.uk/news/education-',
'http://www.bbc.co.uk/news/science_and_enviroment-',
'http://www.bbc.co.uk/news/entertainment_and_arts-',
'http://edition.cnn.com/'
);
// BBC Algorithm
foreach ($links as $link) {
$output = array(
"title" => Titles($link), //dont know what Titles is, variable or string?
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
}
$new_stories = array();
foreach ($output as $new_array) {
if (array_intersect($output['link'], $bbc_values) == true) {
$news_stories[] = $new_array;
}
print_r($news_stories);
}
You decalred the array as $new_stories and printing $news_stories..... diff is 'S'
check whether the code is coming inside this loop or not, i think not...
if (array_intersect($output['link'], $bbc_values) == true) {
echo 'here';
}
Hmm i don't think array_intersect is what you need for a comparison http://php.net/manual/en/function.array-intersect.php
Maybe you want to look for in_array http://php.net/manual/en/function.in-array.php
When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

PHP array_search not working

can anybody let me know why array_search doesnt works for me? All i want is to search value and and get corresponding key value
for eg if i search wiliam i should get 4.. Its simple but aint working for me
<?php
$fqlResult[0]['uid']='1';
$fqlResult[0]['name']='Jay';
$fqlResult[1]['uid']='2';
$fqlResult[1]['name']='UserName2';
$fqlResult[2]['uid']='3';
$fqlResult[2]['name']='Frances';
$fqlResult[3]['uid']='4';
$fqlResult[3]['name']='William';
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname="'".$fqlResult[$i]['name']."'";
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
}
echo "<pre>";
print_r($userdb);
echo "</pre>";
echo array_search('4', $userdb);
?>
It doesn't work because array_seach searches values and "William" is a key. To complicate things, your values and keys are wrapped in single quotes during the for loop.
You'd want to do something like this:
if ( ! empty($userdb["'William'"]) )
{
// Echoes "'4'"
echo $userdb["'William'"];
}
// To find user ID "'4'"
// Outputs "'William'"
echo array_search("'4'", $userdb);
If you don't want things wrapped in single quotes, you'll need to change your for loop as follows:
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['name'];
$userdb[$userdbname]=$fqlResult[$i]['uid'];
}
if ( ! empty($userdb["William"]) )
{
// Outputs "4" (without the single quotes)
echo $userdb["William"];
}
// To find user ID "4" (without the single quotes)
// Outputs "William"
echo array_search('4', $userdb);
array_search() searches values, not keys.
If you want to check the existence of something that you use as a key in an array, you can just use isset:
if(isset($userdb['William'])) {
echo "$userdb[William] is William's uid!";
}
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['uid'];
$userdb[$userdbname]=$fqlResult[$i]['name'];
}
Change
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
with this
$userdb[$i] = "{$fqlResult[$i]['name']}";
array_search only works with arrays of scalar data. You're trying to search an array of arrays. You can easily search the array yourself:
function search_array_col($array, $col, $val)
{
foreach ($array as $key => $a)
{
if ($a[$col] == $val) return $key;
}
return null;
}
echo search_array_col($fqlResult, 'name', 'William') , "\n";
echo search_array_col($fqlResult, 'uid', '4') , "\n";
Edit: n/m, I misread your code. However, you could still use this to search your original array, so I'll leave the answer for reference.
try this:
foreach($fqlResult as $result)
{
$name = $result["name"];
$uid = $result["uid"];
$userdb[$name] = $uid;
}
then you want to use array_key_exists() to find the key. array_search() only works for searching values, not keys.
$nameExists = array_key_exists("William",$userdb);
You can remove the quotes in the $userdbname="'".$fqlResult[$i]['name']."'";
rewrite it to
$userdbname= $fqlResult[$i]['name'];

Foreach and 2D Array in PHP

$mainMenu['Home'][1] = '/mult/index.php';
$mainMenu['Map'][1] = '/mult/kar.php';
$mainMenu['MapA'][2] = '/mult/kara.php';
$mainMenu['MapB'][2] = '/mult/karb.php';
$mainMenu['Contact'][1] = '/mult/sni.php';
$mainMenu['Bla'][1] = '/mult/vid.php';
This is a menu, 1 indicates the main part, 2 indicates the sub-menu. Like:
Home
Map
-MapA
-MapB
Contat
Bla
I know how to use foreach but as far as I see it is used in 1 dimensional arrays. What I have to do in the example above?
You would need to nest two foreach BUT, there is nothing about your data structure that easily indicates what is a sub-item. Map vs. MapA? I guess a human could figure that out, but you'll have to write a lot of boilerlate for your script to sort that.. Consider restructuring your data so that it more closely matches what you are trying to achieve.
Here's an example. You can probably come up with a better system, though:
$mainMenu = array(
'Home' => '/mult/index.php',
'Map' => array(
'/mult/kar.php',
array(
'MapA' => '/mult/kara.php',
'MapB' => '/mult/karb.php'
)
),
'Contact' => '/mult/sni.php',
...
);
You nest foreach statements; Something like this should do the work.
foreach($mainMenu as $key=>$val){
foreach($val as $k=>$v){
if($k == 2){
echo '-' . $key;
}else{
echo $key;
}
}
}
Foreach can just as easily be used in multi-dimensional arrays, the same way you would use a for loop.
Regardless, your approach is a little off, here's a better (but still not great) solution:
$mainMenu['Home'][1] = '/mult/index.php';
$mainMenu['Map'][1] = '/mult/kar.php';
$mainMenu['Map']['children']['MapA'] = '/mult/kara.php';
$mainMenu['Map']['children']['MapB'] = '/mult/karb.php';
$mainMenu['Contact'][1] = '/mult/sni.php';
$mainMenu['Bla'][1] = '/mult/vid.php';
foreach($mainMenu as $k => $v){
// echo menu item
if(isset($v['children'])){
foreach($v['children'] as $kk => $vv){
// echo submenu
}
}
}
That said, this only does 1-level of submenus. Either way, it should help you get the idea!

Categories