How to get all values from an array - php

I have an varible that retrive and stores values in an array format. That is
$fold_location = Input::get('location');
If we Print this means it look like below:
Array ( [0] => 1 [1] => 2 )
What i want is to get all values from this variable.
i am trying the following.
foreach($fold_location as $value) {
$fold_location = $value;
print_r($fold_location);
}
But it return the output as 1.
I want to get all the values. How to do that in php -mysql

You do override your Array in the loop. Try:
foreach($array as $item) print_r($item);
See also http://php.net/manual/en/control-structures.foreach.php

You can get the Array values using the PHP's array_values() function. You need not do a foreach()
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
Output of the above code will be
Array
(
[0] => XL
[1] => gold
)

Replace your foreach loop with below code.
foreach($fold_location as $value) {
echo $value;
}

Related

Using the nth item in a php array

I have created an array, as follows:
$results = array();
do {
$results[] = $row_products;
} while ($row_products = mysql_fetch_assoc($products));
print_r($results);
This prints out the array like this:
Array (
[0] => Array (
[productName] => product1
)
[1] => Array (
[productName] => product2
)
[2] => Array (
[productName] => product3
)
I want to now use say the second item in the array in another mysql query.
But I cannot define it. I have tried
$results[1];
but this does not work.
So in effect, if I echo the second item, it would print 'product2'.
You should learn the basics about arrays here: http://www.php.net/manual/en/language.types.array.php
You are using a nested array, so you have the access it like this:
echo $results[1]['productName'];
Another solution would be to use $results[] = $row_products['productName']; and then just echo $results[1].
In addition, you should use a while loop instead of a do/while loop because $row_products does not seem to be defined for the first iteration.
while ($row_products = mysql_fetch_assoc($products)) {
$results[] = $row_products;
}
try this :
echo $results[1]['productName'] ;
$results[1] is an array, If you want see the array print_r($results[1]);

php, how to grab data from an multidimensional array?

i have an array that looks like this:
foreach($obj as $key => $value)
{
print_r ($obj);
}
Array
(
[id] => 24991526504444
[name] => 21test
[picture] => http://profile.ak.fbcdn.net/hprofile-ak-sn4/276505_2499152255_s.jpg
[link] => http://apps.facebook.com/test/vote=6189373
[likes] => 1
[category] => Website
[parking] => Array
(
[street] => 0
[lot] => 0
[valet] => 0
)
[payment_options] => Array
(
[cash_only] => 0
[visa] => 0
[amex] => 0
[mastercard] => 0
[discover] => 0
)
)
how can i get the data from this array, for ex the id, or the likes.
i've tryed echo $key['likes'] or echo $key[$value['likes']] and some more combinations and it doesn't work
any ideas?
thanks
$key isn't your array, $obj is your array. You should be using $obj['likes'] or $obj['parking']['street']. You don't have to enumerate the keys to access the keys/values within the object, just use $obj.
Also, your foreach doesn't make sense:
foreach($obj as $key => $value)
{
print_r ($obj);
}
This reads "For each key in the array, print the entire array". You don't have to loop at all, the whole purpose of print_r is to recursively print the contents of an array for you with no looping. Just use
print_r($obj);
Please read the manual on arrays.
You don't need a loop to access an array. What you want can be done simply with $obj['id'] or $obj['likes'].
According to this:
foreach($obj as $key => $value)
{
print_r ($obj);
}
the array you have displayed is actually the full structure of $obj and not any of its key=>value pairs.
So you should just need:
echo $obj['likes'];
echo $obj['id'];
You are using foreach, that means you are iterating array elements, you should be using
$obj['likes']
should return the value on the array (1 in your case).
And for the multidimensional ones
$obj['payment_options']['cash_only']
should return the value (0 in your case)

Convert PHP array into Key => Value Array

Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}

Echo a multidimensional array in PHP

I have a multidimensional array and I'm trying to find out how to simply "echo" the elements of the array. The depth of the array is not known, so it could be deeply nested.
In the case of the array below, the right order to echo would be:
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
This is the array I was talking about:
Array
(
[0] => Array
(
[comment_id] => 1
[comment_content] => This is a parent comment
[child] => Array
(
[0] => Array
(
[comment_id] => 3
[comment_content] => This is a child comment
[child] => Array
(
[0] => Array
(
[comment_id] => 4
[comment_content] => This is the 2nd child comment
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[comment_id] => 2
[comment_content] => This is another parent comment
[child] => Array
(
)
)
)
<pre>
<?php print_r ($array); ?>
</pre>
It looks like you're only trying to write one important value from each array. Try a recursive function like so:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
You could also make it a little more dynamic and have the 'comment_content' and 'child' strings passed into the function as parameters (and continue passing them in the recursive call).
Proper, Better, and Clean Solution:
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach ($array as $key => $value)
{
if (is_array($value))
{
Self::traverseArray($value); // Or
// traverseArray($value);
}
else
{
echo $key . " = " . $value . "<br />\n";
}
}
}
You simply call in this helper function traverseArray($array) in your current/main class like this:
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);
source: http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/
print_r($arr) usually gives pretty readable result.
if you wanted to store it as a variable you could do:
recurse_array($values){
$content = '';
if( is_array($values) ){
foreach($values as $key => $value){
if( is_array($value) ){
$content.="$key<br />".recurse_array($value);
}else{
$content.="$key = $value<br />";
}
}
}
return $content;
}
$array_text = recurse_array($array);
Obviously you can format as needed!
There are multiple ways to do that
1) - print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
//-------------------------------------------------
2) - use var_dump($array) to get more information of the content in the array like datatype and length.
//-------------------------------------------------
3) - you can loop the array using php's foreach(); and get the desired output.
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['child']);
}
}
Try to use var_dump function.
If you're outputting the data for debugging and development purposes, Krumo is great for producing easily readable output. Check out the example output.
Recursion would be your answer typically, but an alternative would be to use references. See http://www.ideashower.com/our_solutions/create-a-parent-child-array-structure-in-one-pass/

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Categories