How to get value of an array inside an array - php

Example:
foreach ($AllowAttributes as $attribute) {
$medida_cart = $attribute['options'];
print_r($medida_cart);
}
Displays on the screen Array ( [22] => 5.40 x 2.10 )
I want this value 5.40 x 2.10 without having to use the index
$medida_cart = $attribute['options'][22];
The index 22 will be changed forever, and always will have only one value, example:
Array ([random] => data I need)

Use current() or reset():
$medida_cart = reset($attribute['options']);

$medida_cart = array_values($attribute['options'])[0];
This will make the associative array into a sequential array and get the first and only value.
array_values() DOCUMENTATION

Related

Unset Nested Array by Comparison

Thank you for taking your time to look at this question.
I have a database entry that contains a serialized array (of multiple arrays). It might look like this:
Array 1
a:2:{
i:0;a:3:{s:11:"search_type";s:6:"owners";s:11:"search_text";s:4:"test";s:11:"search_name";s:4:"test";}
i:1;a:5:{s:8:"t_rating";s:3:"Yes";s:9:"t_ranking";s:3:"Yes";s:11:"search_type";s:8:"products";s:11:"search_text";s:5:"test2";s:11:"search_name";s:5:"test2";}
}
Then, I have another serialized array being passed that might look like this:
Array 2
a:2:{s:11:"search_type";s:6:"owners";s:11:"search_text";s:4:"test";}
Conditions
Array 1 can have any number of nested arrays (my example shows 2).
Array 2 is passed from a selector; which should loop Array 1 and remove it's associated nested array.
These arrays are being compared using PHP.
The Problem
The issue is that each array in Array 1 needs to first remove the "search_name" array key before making the comparison.
The "search_name" key from Array 1 should never be used for comparison. When the "search_name" key is removed; a valid comparison of the serialized arrays can then be made.
But, when this gets updated to the db; the non-removed arrays should still contain the "search_name" key. It only needs to be removed for comparison; then it's full array should be removed from Array 1.
My (Broken) Code
Here is what I currently have:
$search_array = unserialize($_POST['search_array']); // Serialized Array 2
$bm_adv_search = $query_adv_search[0]->bm_adv_search; // Serialized Array 1
$unser_array = unserialize($bm_adv_search); // Unserialize Array 1
// Unset search_name from each array in Array 1
foreach($unser_array as $key => $value) {
unset($unser_array[$key]['search_name']); // THIS IS THE PROBLEM AREA
}
// Unset Array 2 from Array 1
if(in_array($search_array, $unser_array)) {
if(($key = array_search($search_array, $unser_array)) !== false) {
unset($unser_array[$key]);
}
}
// Re-Serialize Array 1
$reser_array = serialize($unser_array);
// Update db with Array 1
.....
So when I update Array 1 to the db; the name field has been removed from all nested arrays, which when updated, excludes the "search_name".
I need the "search_name" to stay in each array from Array 1 when updated. I just need to remove it for comparison purposes... and then remove the nested array from Array 1.
The Idea
Basically, I am storing user saved bookmarks. When a user bookmarks an item; a serialized array gets added to Array 1. A user is prompted to enter a "Name" for the search bookmark; hence the "search_name" field.
When a user clicks to remove a bookmark; the "search_name" key is not available in the comparison array (Array 2). Array 1 should be looped for Array 2's existence (minus the "search_name" key)... and the entire matched array (including "search_name") should be unset.
Again, thank you for any time on this question. I really appreciate any assistance.
UPDATE
Got it working. Thanks Mikel!!
Here is the updated code:
$search_array = unserialize($_POST['search_array']); // Serialized Array 2
$bm_adv_search = $query_adv_search[0]->bm_adv_search; // Serialized Array 1
$unser_array = unserialize($bm_adv_search); // Unserialize Array 1
// Clone Array 1
$compare_array = $unser_array;
// Unset search_name from each array in cloned Array 1
foreach($compare_array as $key => $value) {
unset($compare_array[$key]['search_name']);
}
// Unset Array 2 from Array 1
if(in_array($search_array, $compare_array)) {
if(($key = array_search($search_array, $compare_array)) !== false) {
unset($unser_array[$key]);
}
}
// Re-Serialize Array 1
$reser_array = serialize($unser_array);
// Update db with Array 1
.....
Copy your "Array 1" to a temporary array for comparison, but do any true modifications to the main $unser_array.
Could be as simple as $compar_array = $unser_array and then modifying a few of the vars throughout the code.
You can then compare the two by array key, as they keys will be identical in the arrays. (you just created this copy)
Lemme know if you need any help!

increment value inside an array of arrays (if key is non-existent, set it to 1)

Question has been updated to clarify
For simple arrays, I find it convenient to use $arr[$key]++ to either populate a new element or increment an existing element. For example, counting the number of fruits, $arr['apple']++ will create the array element $arr('apple'=>1) the first time "apple" is encountered. Subsequent iterations will merely increment the value for "apple". There is no need to add code to check to see if the key "apple" already exists.
I am populating an array of arrays, and want to achieve a similar "one-liner" as in the example above in an element of the nested array.
$stats is the array. Each element in $stats is another array with 2 keys ("name" and "count")
I want to be able to push an array into $stats - if the key already exists, merely increment the "count" value. If it doesn't exist, create a new element array and set the count to 1. And doing this in one line, just like the example above for a simple array.
In code, this would look something like (but does not work):
$stats[$key] = array('name'=>$name,'count'=>++);
or
$stats[$key] = array('name'=>$name,++);
Looking for ideas on how to achieve this without the need to check if the element already exists.
Background:
I am cycling through an array of objects, looking at the "data" element in each one. Here is a snip from the array:
[1] => stdClass Object
(
[to] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[name] => foobar
[id] => 1234
)
)
)
I would like to count the occurrences of "id" and correlate it to "name". ("id" and "name" are unique combinations - ex. name="foobar" will always have an id=1234)
i.e.
id name count
1234 foobar 55
6789 raboof 99
I'm using an array of arrays at the moment, $stats, to capture the information (I am def. open to other implementations. I looked into array_unique but my original data is deep inside arrays & objects).
The first time I encounter "id" (ex. 1234), I'll create a new array in $stats, and set the count to 1. For subsequent hits (ex: id=1234), I just want to increment count.
For one dimensional arrays, $arr[$obj->id]++ works fine, but I can't figure out how to push/increment for array of arrays. How can I push/increment in one line for multi-dimensional arrays?
Thanks in advance.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
// this next line does not meet my needs, it's just to demonstrate the structure of the array
$stats[$obj->id] = array('name'=>$obj->name,'count'=>1);
// this next line obviously does not work, it's what I need to get working
$stats[$obj->id] = array('name'=>$obj->name,'count'=>++);
}
Try checking to see if your array has that value populated, if it's populated then build on that value, otherwise set a default value.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
if (!isset($stats[$obj->id])) { // conditionally create array
$stats[$obj->id] = array('name'=>$obj->name,'count'=> 0);
}
$stats[$obj->id]['count']++; // increment count
}
$obj = $element->to->data is again an array. If I understand your question correctly, you would want to loop through $element->to->data as well. So your code now becomes:
$stats = array();
foreach ($dataArray as $element) {
$toArray = $element->to->data[0];
foreach($toArray as $toElement) {
// check if the key was already created or not
if(isset($stats[$toElement->id])) {
$stats[$toElement->id]['count']++;
}
else {
$stats[$toElement->id] = array('name'=>$toArray->name,'count'=>1);
}
}
}
Update:
Considering performance benchmarks, isset() is lot more faster than array_key_exists (but it returns false even if the value is null! In that case consider using isset() || array_key exists() together.
Reference: http://php.net/manual/en/function.array-key-exists.php#107786

Extract each value from an associative array with unknown length and value names

I have an array like:
Array
(
[item1] => value1
[item2] => value
[item3] => value3
)
And I want to extract all the names and values to variables.
But say, I don't know the names of items that the array contains.
I wanna generate variables for each array item with the name of this item name in array to make possible of using this variables later.
The result should look like this:
item_name1 = item_value1
item_name2 = item_value2
item_name3 = item_value3
Seems the foreach loop should be usefull here.
I'm not sure if I understood this.
If you want the key from the array to become a variable with the same name you can use the extract function: http://php.net/manual/en/function.extract.php
Using built-in functions is always faster, but if you need the foreach approach with $$:
foreach ($array as $key=>$val)
{
$$key = $val;
}

PHP json_decode array cannot retrieve numerical index?

I have an array that is associative that I have decoded from a json json_decode second value true and looks like
Array (
[test] => Array
(
[start] => 1358766000
[end] => 1358775000
[start_day] => 21
[end_day] => 21
)
)
But for some reason when I do $array[0] I get null? How can I get the array by index? Not by key name?
array_values() will give you all the values in an array with keys renumbered from 0.
The first level of the array is not numerical, it's an associative array. You need to do:
$array['test']['start']
Alternatively, to get the first element:
reset($array);
$first_key = key($array);
print_r($array[$first_key]);
You could use current.
$first = current($array); // get the first element (in your case, 'test')
var_dump($first);
This is by design . . . your JSON used a key (apparently test), which contained a JSON object. The keys are preserved when you do a json_decode. You can't access by index, though you could loop through the whole thing using a foreach.
From your comment, it sounds like you want to access previous and next elements from an associative array. I don't know a way to do this directly, but a hackish way would be as follows:
$testArr = array('a'=>'10', 'b'=>'2', 'c'=>'4');
// get numeric index of the element of interest
$keys = array_keys($testArr);
$i = array_search('b', $keys);
// get key of next element
$nextElementKey = $keys[$i+1];
// next element value
$nextElementValue = $testArry[$nextElementKey];
// get key of previous element
$prevElementKey = $keys[$i-1];
// prev value
$[prevElementValue = $testArry[$prevElementKey];
You'd probably want to add some error checking around the previous and next key calculations to handle the first and last values.
If you don't care about the data in the key, Ignacio's solution using array_keys is much more efficient.

How to detect duplicate php Array

I have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )
How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);
but it seem like not work for me.
any idea on this?
thanks for advance.
I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
// array has no duplicated values
} else {
// array has duplicated values - see compared arrays
}
Are you looking for array_unique?
You can use array_unique() to remove duplicate values. If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
//tell participant to re=fill their data
}

Categories