Append string to an exitsting array key? PHP - php

I want to append the key from $teasers to the key of the array contained within each $teasers element and then create an associative array that contains the appended keys for its key and the content of the sub array for its content. Following? I hope so, if not here's an example of my desired end product:
This is a simplified version of the multidimensional array I'm working with:
$teasers[0]=array('id' => 4,
'title' => 'How to determine the speed of an african swallow',
'content'=> 'Its really quite simple...')
$teasers[1]=array('id' => 5,
'title' => 'Man alleged to be cereal killer after breakfast',
'content' => 'Turns out eating a delicious bowl of froste...')
I'm working towards turning it into this:
$data Array(
'/*Key from subarray+$teasers key*/' => '/*content from subarray*/',
'id0' => '4',
'title0' => 'How to determine the speed of an african swallow',
'content0' => 'Its really quite simple...',
'id1' => '5',
'title1' => 'Man alleged to be cereal killer after breakfast',
'content1' => 'Turns out eating a delicious bowl of frosted...')
Still not following? I don't blame you. Maybe this will help. I was originally going about it like this until I realized you can't pass a variable into a foreach loop. ):
foreach ($teasers as $key => $blogentry) {
foreach($blogentry as $entrykey => $content){
//Basically I would like to append $key to the end of $entrykey
//so that I can essentially access all of the data from one array($data[])
$data[$entrykey.$key] = $content;
}
}
I'm more than happy to do anything I can to make things more clear or help you help me. Thanks for your time in advance!!

I think your code should work. Add $data = array(); before your loops.

Related

PHP Random generator from array issues

So I have done some research and fixed most of the issues but I can't find out why this is giving me a Notice: Undefined index: in Line 344
If you guys have any suggestion it would be greatly appreciated :D
Here is my Array:
$quote = array(
1 => array(
"quote" => 'The early bird gets the worm, but the second mouse gets the cheese...',
"name" => 'Stephen Wright'
),
2 => array(
"quote" => 'Your time is limited, so dont waste it living someone elses life.',
"name" => 'Steve Jobs'
),
3 => array(
"quote" => 'When one door closes, another one opens. Or you could jut re-open the closed door. Because thats how doors work.',
"name" => "Anon."
),
4 => array(
"quote" => "The two most important days in your life are the day you are born and the day you find out why.",
"name" => "Mark Twain"
),
5 => array(
"quote" => "Before you criticize someone, you should walk a mile in their shoes, that way when you criticize them, you're a mile away and you have their shoes.",
"name" => "Anon."
),
);
$random=array_rand($quote,1);
And my output:
[This is line 344]
<?php
echo $quote[$random[0]]
?>
If you only get 1 array key with array_rand(), then you don't get an array back, just the key. As you can see in the manual:
When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. [...]
So after this you try to access the number as an array which doesn't work. So just remove the index from it, e.g.
echo $quote[$random]
//^ See here removed
Since it is a two dimension array you also have to sepcify the second dimesion if you want to use echo to print the value, e.g.
echo $quote[$random]["quote"];
echo $quote[$random]["name"];

PHP multi-dimentional array sort

I have an array that I would like to sort, that should be easy, except that I build my array in a strange manners (for different reasons) that make it hard to sort. Here is my array :
$arrayCEO =array(
'companyName' => array(0=>'name1', 1=>'name2'),
'link' => array (0=>'link1', 1=>'link2'),
'isin' => array (0=>'isin1', 1=>'isin2'),
'mktCap' => array (0=>'mktCap1', 1=>'mktCap2'),
'nbShares' => array (0=>'nbShares1', 1=>'nbShares2'),
'amount' => array (0=>'10', 1=>'20'));
Is that possible to sort by "amount" without breaking the order in the others arrays?
Do you recommend me to rewrite my code to build an array like this one :
$arrayCEO =array(
0 => array ('name' => 'name1', 'link' => 'link1', 'isin' => 'isin1', …),
1 => array ('name' => 'name2', 'link' => 'link2', 'isin' => 'isin2', …));
2 => ...
I know this one would be simple to sort but it's a lot of work to rewrite my piece of code.
Thanks,
Dorian
It makes a lot more sense to rewrite your arrays to store in the more conventional format you described - (It's always better to organise things in decreasing magnitude 'Root > rows > fields' instead of 'Root > fields > rows')
If you didn't want to change you could probably use the usort function and roll your own sorting method, but it might be a bit of work to make it play nicely.

Retrieve first key in multi-dimensional array using PHP

I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.

How can i use different string value's in one function?

First i am a beginner in programming in general, i am trying to create a program for using gps locations from Lightroom on a map in googlemaps.
When i use the print the strings below ti the screen i see 5 different value's, this is also what i want, but...
I want to create also 5 different markers on the map this is done by the addMarkerByCoords Function but how can i use the 5 value per strings in the function ?
I have tried array, foreach but i cannot getting to work. The not working part can and probably will be my fault. LOL
print_r ("$Loncoord");
print_r ("$Latcoord");
print_r ("$gui");
//$map->formatOutput = true;
$map->addMarkerByCoords("$Loncoord","$Latcoord","$gui",'<b>Old Chicago</b>');
Can somebody give me a hint ?
To: Jonathan Sampson:
outputs print_r :-5.68166666667, +24.6513888889,IMG_3308,index.html,Landschap
To: Anti Veeranna I removed the " marks (and the program still works), but can you explain why this is better ?
And to the others Thank you very very much for the effort,work and really quick responses.
Assuming that this is PHP, you could us an array of arrays, and then loop.
Something like this:
$items = array(
array(
'long' => 12.34567,
'lat' => 34.56789,
'gui' => '????',
'location' => 'old chicago'
),
...
array(
'long' => 12.34567,
'lat' => 34.56789,
'gui' => '????',
'location' => 'old chicago 5'
)
);
foreach ($items as &$item) {
$map->addMarkerByCoords(
$item['long'],
$item['lat'],
$item['gui'],
$item['location']
);
}
unset($item);
$map->addMarkerByCoords(Array($Loncoord, $Latcoord, $gui, '<b>Old Chicago</b>));
??

Count Similar Array Keys

I have a POST request coming to one of my pages, here is a small segment:
[shipCountry] => United States
[status] => Accepted
[sku1] => test
[product1] => Test Product
[quantity1] => 1
[price1] => 0.00
This request can be any size, and each products name and quantity's key would come across as "productN" and "quantityN", where N is an integer, starting from 1.
I would like to be able to count how many unique keys match the format above, which would give me a count of how many products were ordered (a number which is not explicitly given in the request).
What's the best way to do this in PHP?
Well, if you know that every product will have a corresponding array key matching "productN", you could do this:
$productKeyCount = count(preg_grep("/^product(\d)+$/",array_keys($_POST)));
preg_grep() works well on arrays for that kind of thing.
What Gumbo meant with his "use array instead" comment is the following:
In your HTML-form use this:
<input type="text" name="quantity[]" />
and $_POST['quantity'] will then be an array of all containing all of your quantities.
If you need to supply an id you can also do this:
<input type="text" name="quantity[0]" />
$_POST['quantity][0] will then hold the corresponding quantity.
As mentioned by gumbo you could group all parameters describing one item in its own array which usually makes it easier to iterate them. You may not have control over the POST parameters but you can restructure them like e.g. with
<?php
$testdata = array(
'shipCountry' => 'United States',
'status' => 'Accepted',
'sku1' => 'test1',
'product1' => 'Test Product1',
'quantity1' => '1',
'price1' => '0.01',
'sku2' => 'test2',
'product2' => 'Test Product2',
'quantity2' => '2',
'price2' => '0.02'
);
$pattern = '/^(.*\D)(\d+)$/';
$foo = array('items'=>array());
foreach($testdata as $k=>$v) {
if ( preg_match($pattern, $k, $m) ) {
$foo['items'][$m[2]][$m[1]] = $v;
}
else {
$foo[$k] = $v;
}
}
print_r($foo);
Though there be plenty of examples, if you're guaranteed that the numbers should be contiguous, I usually take the approach:
<?php
$i = 1;
while( isset($_POST['product'.$i) )
{
// do something
$i++;
}

Categories