Get value from array : PHP [duplicate] - php

This question already has answers here:
How to access a specific value in a mixed object(stdClass) and array construct?
(2 answers)
Closed 8 years ago.
var_dump($resultData);
gives me this
array(3) {
[0]=>
object(stdClass)#1 (2) {
["name"]=>
string(12) "filterName_1"
["value"]=>
string(8) "language"
}
[1]=>
object(stdClass)#2 (2) {
["name"]=>
string(9) "country_1"
["value"]=>
string(0) ""
}
[2]=>
object(stdClass)#3 (2) {
["name"]=>
string(10) "language_1"
["value"]=>
string(4) "UAE1"
}
}
How to itrate and get the values ?
tried
echo $resultData["name"];
and some other combinations but cannot make it work.
EDIT : NOTE :
As i have to get the loop of 3 items and its values i need to get the value in the loop as
for ($i=0; $i+3 <= count($resultData); $i=$i+3)
{
}
is there a way without foreach looping?

May you should try
<?php
foreach($resultData as $key => $value) {
echo $value->name; // Give you all names
}
Another example:
<?php
// Set keys you need to print
$requiredKeys = array('name', 'value');
// Iterate the array
foreach($resultData as $key => $value) {
// Iterate the required keys
foreach($requiredKeys as $reqVal) {
// Check, if propertie exists in current object
if(isset($value->{$reqVal}) {
echo $value->{$reqVal}; // Give you all names
}
}
}
Example without foreach (for-loop):
<?php
// Set keys you need to print
$requiredKeys = array('name', 'value');
// Iterate the array
for($currentElement = 0; $currentElement <= count($resultData) as $currentElement++) {
// Iterate the required keys
for($reqCounter = 0; $reqCounter <= count($requiredKeys); $reqCounter++) {
// Check, if propertie exists in current object
if(isset($resultData[$currentElement]->{$requiredKeys[$reqCounter]}) {
echo $resultData[$currentElement]->{$requiredKeys[$reqCounter]}; // Give you all names
}
}
}

$resultData is an array containing multiple objects, therefore the first object can be accessed with $resultData[0] and so on.
The objects have a property named name, which can be accessed with $object->name
If you have more than one object in the array, then you can loop through the values contained in the array with foreach. For example:
foreach ($resultData as $object) {
if($object->name === MY_NAME) {
echo $object->value;
}
}
This will take each object in the array and display its value if its name equals MY_NAME.

echo $resultData[0]->name;
Give that a try

Related

Remove duplicates from PHP which has multiple arrays [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
This is the current output I have from an array by doing var_dump($getvals):
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
What I want to achieve is first of all, to ignore the ['label'] tables and then try removing any duplicates (150mm and 125mm). I have tried both array_unique and !inarray() but it won't work. Here is my code:
$getvals = get_sub_field('option_diameter'); // This is my array
$takens = array(); // I create an empty array for later on
foreach ($getvals as $key => $getval){ // Running through the array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($getval, $takens)){ // Check if the current value is already inside $takens array
$takens[] = $getval; // If not, then put it
}
}
}
var_dump($takens); // The output is below
This is what I get from var_dump($takens) :
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "125mm"
}
array(1) {
[0]=>string(5) "125mm"
}
The duplicate values are not removed. Any ideas?
Use a key to remove the duplicate, Demo
$result = [];
foreach($array as $arr){
$result[$arr['value']] = $arr;
}
print_r(array_values($result));
You need to first fetch value by using array_diff_key. Then you need to use array_column, in which passing null as second parameter and unique by value as key to removing duplicates(as keys can not be duplicated). Then to reset indexes array_values
Here is the script,
$takens = array_values(array_column(array_map(function ($a) {
return array_diff_key($a, ['label' => '']);
}, $getvals), null, 'value'));
Demo
Output:-
array(2) {
[0]=>
array(1) {
["value"]=>
string(5) "150mm"
}
[1]=>
array(1) {
["value"]=>
string(5) "125mm"
}
}
You can use array_column
$r = array_values(array_column($a, null, 'label'));
OR
if you want to keep single column
$r = array_values(array_column($a, 'value', 'label'));
print_r($r);
array_values will reorder the keys of the array
Working example :- https://3v4l.org/n8SA1
It look like you forgot a foreach.
Here a test done a few minutes ago :
$aArrayTest = array (
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
)
);
$aArrayResult = array();
foreach ($aArrayTest as $aArray) { // Running through the array of Arrays
foreach ($aArray as $key => $value){ // Running through each array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($value, $aArrayResult)){ // Check if the current value is already inside $takens array
$aArrayResult[] = $value; // If not, then put it
}
}
}
}
var_dump($aArrayResult);</pre>

Building a multidimensional Array with another Array in PHP

I try to build an array. I don't wanna write something like $array[3][5][8] = []. Because the count of the first Array can change, here it's 3 but it also can be like 9 or 12. Also the values can change, but they are always unique numbers. I hope someone knows a better way. Thank you.
// First Array, which I have. The count and the content can change.
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "8"
}
// Second Array, thats the goal.
array(1) {
[3]=>
array(1) {
[5]=>
array(1) {
[8]=>
array(0) {
}
}
}
}
This code will solve your problem:
$array = [3,5,8,9]; // your first array
$newArray = null;
foreach ($array as $value) {
if($newArray === null) {
$newArray[$value] = [];
$ref = &$newArray[$value];
}
else {
$ref[$value] = [];
$ref = &$ref[$value];
}
}
$newArray - holds the result you wanted
$array1=array(3,5,8);
$array2=array();
for($i=count($array1);$i>0;$i--){
$temp=array();
$temp[$array1[$i-1]]=$array2;
$array2=$temp;
}
$subject is the reference to the array you are currently in.
$array is the main root array that you obtain in the end.
$input is the input int array.
$subject = $array = [];
foreach($input as $key){
$subject[$key] = []; // create empty array
$subject =& $subject[$key]; // set reference to child
// Now $subject is the innermost array.
// Editing $subject will change the most nested value in $array
}

Create a n.2 PHP array from JSON output

I'm using
$data=json_decode($response,true)
the output is
array(3)
{
["instrument"]=> string(7) "EUR_USD" ["granularity"]=> string(1) "D" ["candles"]=> array(10)
{
[0]=> array(7)
{
["time"]=> string(27) "2016-09-26T21:00:00.000000Z" ["openMid"]=> float(1.125495) ["highMid"]=> float(1.1259) ["lowMid"]=> float(1.119125) ["closeMid"]=> float(1.121605) ["volume"]=> int(17059) ["complete"]=> bool(true)
}
[1]=> array(7)
{
["time"]=> string(27) "2016-09-27T21:00:00.000000Z" ["openMid"]=> float(1.1218) ["highMid"]=> float(1.12369) ["lowMid"]=> float(1.118215) ["closeMid"]=> float(1.12171) ["volume"]=> int(17915) ["complete"]=> bool(true)
}
}
}
I want to create two arrays with the values openMid and closeMid for example:
$open=array(1.125495,1.1218)
$close=array(1.121655,1.12171)
I have to develop the foreach code in order to achieve that.
Anyone can help me? Thanks
Check out the solution below:
$open= []; //Declare empty array to hold openMid values
$close= []; //Declare empty array to hold closeMid values
#Loop through $array
foreach ($array as $key => $value) {
#If any of the value is an array
if (is_array($value)) {
$arr= $value; //Store the array
}
}
//Loop through the second array
foreach ($arr as $val) {
//If the value is of index openMid
if ($val->openMid) {
$open[]= $val->openMid; //Push into the $open array holder
}
//If the value is of index closeMid
if ($val->closeMid) {
$close[]= $val->closeMid; //Push into the $close array holder
}
}

Recursive function for checking multidimensional arrays

Really struggling with this. I have a multidimensional array n levels deep. Each 'array level' has information I need to check (category) and also check if it contains any arrays.
I want to return the category ids of all the arrays which have a category and do not contain an array (i.e. the leaves). I can echo output properly, but I am at a loss as how to return the ids in an array (without referencing)
I have tried RecursiveIteratorIterator::LEAVES_ONLY and RecursiveArrayIterator but I don't think they work in my case? (Maybe I am overlooking something)
$array
array(2) {
["1"]=>
string(5) "stuff"
["2"]=>
array(2) {
["category"]=>
string(1) "0"
["1"]=>
array(3) {
[0]=>
array(3) {
["category"]=>
string(1) "1"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["category"]=>
string(1) "2"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["1"]=>
string(5) "stuff"
["32"]=>
string(5) "stuff"
}
}
}
}
My function
public function recurs($array, $cats = [])
{
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$this->recurs($value, $cats);
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return $array_cat;
}
}
Calling it
$cats_array = $this->recurse($array)
Output echoed
echoing the category here works fine: 1
echoing the category here works fine: 2
How do I return the ids in an array to use in the $cats_array variable?
EDIT: The output should match the echo, so I should get an array containing (1, 2) since they are the only arrays with categories and no arrays within them
array(2){
[0]=>
int(1) "1"
[1]=>
int(1) "2"
}
If I understood you correctly this function will do the job:
function getCategories(array $data)
{
if ($subArrays = array_filter($data, 'is_array')) {
return array_reduce(array_map('getCategories', $subArrays), 'array_merge', array());
};
return array_key_exists('category', $data) ? array($data['category']) : array();
}
If the array contains any sub-arrays they will be returned by array_filter and you will enter the if statement. array_map will apply the function recursively to the sub-arrays and array_reduce will merge the results.
If the array doesn't contain any sub-arrays you will not enter the if statement and the function will return an array with the category if it is present.
Note that you might need to use array_unique to return unique categories.
Also for small performance optimization instead of array_key_exists you can use isset($array[$key]) || array_key_exists($key, $array).
Update
If you want to update your function to make it work you have to recursively collect and merge the sub results. In the following example I introduced a new variable for this:
public function recurs($array, $cats = [])
{
$result = [];
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$result = array_merge($result, $this->recurs($value, $cats));
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return [$array_cat];
}
return $result;
}

How to edit mulltidimensional array elements in php?

this is my array:
$array= array(3) {
[0]=> array(3) { ["name"]=> "one" ["com"]=> "com1" ["id"]=> "1" }
[1]=> array(3) { ["name"]=> "two" ["com"]=> "com2" ["id"]=> "2" }
[2]=> array(3) { ["name"]=> "three" ["com"]=> "com3" ["id"]=> "3" }
I need posibility to change values of name and com for specific id. I try some examples from Stack questions:
1.Link1
foreach($array as &$value){
if($value['id'] == 1){
$value['name'] = 'test';
$value['com'] = 'test';
break; // Stop the loop after we've found the item
}
}
But it don't work. no error but no result too.
2.Link 2
Again,no error message,but no result...
I also try a lot of other examples from Stack but fake,and finaly to write a question..
Buy,
P
Since you are not changing your array value that's why it's-not giving you desired output. Try this:-
foreach($array as $key => &$value){
if($key == 1){
$array[1]['name'] = 'test';// change value to original array
$array[1]['com'] = 'test'; //change value to original array
break; // Stop the loop after we've found the item
}
}
for($i=0;$i<count($array);$i++) {
if($array[$i]['id'] == 1) {
$array[$i]['name'] = 'test';
$array[$i]['com'] = '';
break;
}
}
print_r($array);
If you are able to change the array on creation I would recommend shifting the id to the array's key identifier. Would make life a lot easier to just do:
$array[1]['name'] = 'test';
Otherwise use the for loop posted above and look it up. (Right awnser)

Categories