How to get one part of a multidimensional array using php? - php

I have a problem with a multidimensional array, I want to save specific parts of an array to later show the information on the page but I just cant get it to work
this is the Array when I var_dump it:
array(1) {
["500040477"]=> array(1) {
["statistics"]=> array(1) {
["all"]=> array(1) {
["frags"]=> int(23816)
}
}
}
}
now I want to get the frags and be able to save the int in a extra array/variable
I tried a lot and nothing works even the "common" method to access it doesn't work :(

In the case showed in your example:
$frags = $nameOfYourArray["500040477"]["statistics"]["all"]["frags"];
For arrays with the first key with different name (instead of 500040477):
$arrayFirstkey = current($array);
$frags = $arrayFirstkey["statistics"]["all"]["frags"];
See current PHP function.

If you want to save specific parts of an array ,you can write your own function for this
//first param arra ,second param key
function findByKey($array,$k) {
if(isset($array[$k])) {
return $array[$k];
}
else {
if(is_array($array)) return findByKey(current($array),$k);
else return "Key don't exist";
}
}
You can use above function to get specific array value using key .As your question
findByKey($yourarray,"frags");

Related

What is the correct syntax for detecting an empty 2D array in PHP?

What is the correct syntax to detect an empty 2 Dimensional array in PHP? I have attempted to do so myself using the functions "isset()" and "!empty()" for both "2dArray[0]" and "2dArray[0][0]", but even with an empty array the result comes back positive. Here is a snippet of code from one of the times where I tried this:
if(isset($strengths[0][0]) || isset($sizes[0][0]))
{
print_r($strengths[0][0]);
echo "<br>blah<br>";
print_r($sizes[0][0]);
}
Yet the arrays are both empty. Using print_r we can even see that the arrays return nothing. Here is a picture example of a different attempt using isset(2dArray[0]):
In the picture you can see the array is also empty again.
It's important to note that I can use 2dArray[1] perfectly; it detects that there there is no second row as expected, but that means I cannot have any instances where there is only 1 row in either 2D array because it is positioned at position 0 with nothing at position 1 to be detected anyway.
What am I doing wrong?
Edit 1:
The code:
var_dump($strengths[0][0]);
var_dump($sizes[0][0]);
returns:
array(0) { }
array(0) { }
and the code:
var_dump($strengths[0]);
var_dump($sizes[0]);
returns:
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
Edit 2:
This is my init:
$sizes[][] = array();
This is where data is set:
foreach($products as $product)
{
//product information
foreach($mods as $mod)
{
//mod information
//when array is empty $mods is empty
if ($modType == "SIZE")
{
$sizes[$si][0] = $modValue . $modValueSuffix;
$sizes[$si][1] = $modPrice;
$sizes[$si][2] = $modID;
$si++;
$strengthOrSize = true;
}
}
}
I believe I should have done $sizes[] = array(); for a 2D array. I overlooked this because it's such a short piece of code I did not give it much attention.
You can do this to detect if the sub array is empty:
$arr = [[]];
if (!count($arr[0])) {
// do stuff
}

store multiple values in associative array and return that array in php

I have seen a lot of answers (so please don't mark it duplicate) to store values in associative array but I want to return that array in PHP. Here is my code. It prints all values but only return the first value. I want the whole array returned to use in another function.
Please help
function xml_parsing($response,$size,$array)
{
for($k=0;$k<$size;$k++)
{
$price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice->FormattedPrice;
$myarray[$k]=explode(',',$array["ItemId"]);
$update_fields=array('sku','price');
if($price=='')
{
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
}
else
{
$price_trimed=ltrim($price,'$');
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
// I store the values here using a loop
}
}
print_r($Col_array);
return $col_array; //but here it return only first value
// But I want to return the whole array**
// I can't return it inside loop because it terminates
// the loop and the function
}
Some pseudocode:
//first, initialize empty array:
$Col_array = [];
//do the loop thing.
while(...){
//inside the loop:
//add to array:
$Col_array []= array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
}//loop ends here
print_r($Col_array); //<----- all values.
return $Col_array;
notice how one uses []= to append to an array.
Actually, the mistake here is you are not storing the data that is traversed in the loop. You need to push $Col_array to the main array to get the desired outcome. Here is your code
function xml_parsing($response,$size,$array)
{
//create an empty array before entering the for loop.
$main_array = array();
for($k=0;$k<$size;$k++)
{
$price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice->FormattedPrice;
$myarray[$k]=explode(',',$array["ItemId"]);
$update_fields=array('sku','price');
if($price=='')
{
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
}
else
{
$price_trimed=ltrim($price,'$');
$Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
// I store the values here using a loop
}
//Here you push the $col_array to main_array
array_push($main_array,$Col_array);
//This will store whole bunch of data as multi dimensional array which you can use it anywhere.
}
print_r($main_array);
return $main_array;
}
I think you will get what you desired.
Here I want to answer my own question
function xml_parsing($response,$size,$array)
{
for($k=0;$k<$size;$k++)
{
$price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice-
>FormattedPrice;
//echo "PKkkkkkkkk".$array["ItemId"]."llllll";
$myarray[$k]=explode(',',$array["ItemId"]);
//print_r($myarray[$k]);
$update_fields=array('sku','price');
if($price=='')
{
// $Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
/*Here is the solution we have to index it inside the loop like a 2D
array now it contain an array inside which array of key value pair is
present (associative array) which i wanted */
//**********
$Col_array[$k]['sku']=$myarray[$k][$k];
$Col_array[$k]['price']="-1";
//*********
}
else
{
$price_trimed=ltrim($price,'$');
// final array to be stored in database
// $Col_array=array('sku'=>"".$myarray[$k]
[$k]."",'price'=>$price_trimed);
$Col_array[$k]['sku']=$myarray[$k][$k];
$Col_array[$k]['price']=$price_trimed;
}
}
return $Col_array;
}
//*******
//To Print the returned array use
foreach ($Col_array as $value) {
print_r($value);
}
//*********

Get value out of Array

I am trying to get a certain value out of an array.
Example of the array is:
array(2) {
["error"]=>
array(0) {
}
["result"]=>
array(1) {
["open"]=>
array(1) {
["12345-AAAAA-66AAKK"]=>
array(14) {
["inf"]=>
Usually when I want a certain value I would use:
$datawanted=$data[result][open][value];
However, in this case the first array is a variable that always changes (12345-AAAAA-66AAKK), I need to find the value of that.
I tried getting this with reset() and key[0] but this not give the wanted result.
Is there a way to get the output of the first element in the result array?
You can use array_search: http://php.net/manual/de/function.array-search.php
Example:
foreach ($array['result']['open'] as $dynamicKey => $item) {
if ($key = array_search('Value you are looking for', $item) {
$datawanted=$array['result']['open'][$dynamicKey][$key];
}
}
$data[result][open] is not a correct way to access array items.
The token result looks like a constant. PHP searches for a constant named result, cannot find one and triggers a notice. Then it thinks "I guess the programmer wanted to write 'result' (a string, not a constant). I'll convert it as string to them." and uses 'result' instead.
It works but it's a horrible practice. It dates from the prehistory of PHP, 20 years ago and it's not recommended.
After you fix your code to correctly denote the keys of an array, the next step is to pick one of the many PHP ways to access values in the array.
You can get the first value of an array without knowing its key ($data['result']['open']['12345-AAAAA-66AAKK']) by using the function reset():
$datawanted = reset($data['result']['open']);
Or you can use the function array_values() to get only the values of the array (the keys are ignored, the returned array have the values indexed from zero) then your desired data is at position 0 on this array:
$values = array_values($data['result']['open']);
$datawanted = $values[0];
Another option, if you don't need to keep $data for further processing, is to use the PHP function array_shift() to remove the first value from the array and return it. Be warned that this function modifies the array it receives as argument:
$datawanted = array_shift($data['result']['open']);
If you need to process all the values of $data['result']['open'] (and you probably do) then the best way is to use the foreach PHP statement. It allows you to access both the key and the value of each element of the array:
foreach ($data['result']['open'] as $key => $value) {
// $key is '12345-AAAAA-66AAKK'
$datawanted = $value;
}

php - push array into an array -(pushing both key and the array)

I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.
It might be best if I show to you
foreach ($fields as $f)
{
if ($f == 'Thumbnail')
{
$thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
array_push($newrow, $thumnail);
}
else
{
$newrow[$f] = $row[$f];
}
}
The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .
Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.
array(4) { ["Product ID"]=> string(7) "1007520"
["SKU"]=> string(5) "G1505"
["Name"]=> string(22) "150mm Oval Scale Ruler"
array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }
I would really appreciate any advice.
All you really want is:
$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
You can use array_merge function
$newrow = array_merge($newrow, $thumnail);
Alternatively, you can also assign it directly to $newrow:
if ($f == 'Thumbnail')
$newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...
Or if you want your code to be shorter:
foreach($fields as $f)
$newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];
But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k

Array key exists but can't be read from a cookie

This is a weird one, so bear with me. Asking you guys really is my last resort.
To be clear, I'm using Kohana 3.3, although I'm not even sure that's related to the problem.
I'm using a cookie to track read items on a website. The cookie contains a json_encoded array. Adding to that array isn't a problem, objects are added every time a new item is read. An item in the array contains an object with the last_view_date and a view_count For the sake of updating the view count, I need to check whether the item has been read already using array_key_exists and then add to the view count. Here's how I'm setting the cookie:
// Get the array from the cookie.
$cookie_value = Cookie::get_array('read_items');
// Update the view_count based on whether the id exists as a key.
$view_count = (array_key_exists($item->id, $cookie_value)) ?
$cookie_value[$item->id]['view_count'] + 1 : 1;
// Create the item to be added to the cookie.
$cookie_item = array(
'last_view_date' => time(),
'view_count' => $view_count
);
// Push $cookie_item to the cookie array.
Cookie::push('read_items', $item->id, $cookie_item);
I've added two methods to Kohana's Cookie class, Cookie::push and Cookie::get_array, used in the code above:
class Cookie extends Kohana_Cookie {
public static function push($cookie_name, $key, $value)
{
$cookie_value = parent::get($cookie_name);
// Add an empty array to the cookie if it doesn't exist.
if(!$cookie_value)
{
parent::set($cookie_name, json_encode(array()));
}
else
{
$cookie_value = (array)json_decode($cookie_value);
// If $value isn't set, append without key.
if(isset($value))
{
$cookie_value[$key] = $value;
}
else
{
$cookie_value[] = $key;
}
Cookie::set($cookie_name, json_encode($cookie_value));
}
}
public static function get_array($cookie_name)
{
return (array)json_decode(parent::get($cookie_name));
}
}
Now, here's my problem. Running a var_dump on $cookie_value outputs the following:
array(1) {
["37"]=>
object(stdClass)#43 (2) {
["last_view_date"]=>
int(1359563215)
["view_count"]=>
int(1)
}
}
But when I try to access $cookie_value[37], I can't:
var_dump(array_key_exists(37, $cookie_value));
// Outputs bool(false);
var_dump(is_array($cookie_value));
// Outputs bool(true);
var_dump(count($cookie_value));
// Outputs int(1);
var_dump(array_keys($cookie_value));
// Outputs:
// array(1) {
// [0]=>
// string(2) "37"
// }
Added debugging code:
var_dump(isset($cookie_value["37"]));
// Outputs bool(false).
var_dump(isset($cookie_value[37]));
// Outputs bool(false).
var_dump(isset($cookie_value[(string)37]));
// Outputs bool(false).
I hope it's clear enough.
Take a look at json_decode. Currently, you're casting the result to an array. If you pass true as the second parameter to json_decode, you'll get an array back instead of a stdObject.
The problem may also be related to you checking int vs string keys. You could test by running this code on your server:
<?php
$one = array("37" => "test");
$two = array(37 => "test");
var_dump(array_key_exists(37,$one)); // true or false?
var_dump(array_key_exists(37,$two)); // true
?>
Access the value using:-
$cookie_value["37"]
"37" (key) is in string format.. You are specifying it as integer ($cookie_value[37])

Categories