Is there a way to access a json object elements using PHP - php

I am trying to get a data from my own API using PHP \
My PHP code :
$cart = json_decode(file_get_contents("php://input",true));
foreach ($cart->thoubss as $a){
echo($a['0']); // trying to get the first element in the array (4) in the first iteration and then (3) in the second iteration
echo($a['1']); // trying to get the first element in the array (5) in the first iteration and then (3) in the second iteration
}
My JSON input :
{"thoubss":"{'0': [4, 5], '1': [5, 3]}"}
I am getting
PHP Warning: Invalid argument supplied for foreach()
print_r($cart) output
stdClass Object
(
[thoubss
] => {'0': [
4,
5
], '1': [
5,
3
]
}
)

Try with
$cart = json_decode(file_get_contents("php://input",true),true);
json_decode will return an array instead of an stdClass object

You can use this method also.
$cart = json_decode(file_get_contents("php://input",true),true);
This will return an array like below.
$cart = array(
"thoubss" => array(
'0' => array(4, 5),
'1' => array(5, 3)
)
);
Now you can use like below:
foreach ($cart['thoubss'] as $a){
echo $a[0];
echo $a[1];
}

Related

How can I assign properties to an object in php specifically using array_reduce? [duplicate]

This question already has answers here:
How to convert an array to object in PHP?
(35 answers)
PHP array_reduce with initial parameter as an array
(5 answers)
Closed 19 days ago.
This post was edited and submitted for review 19 days ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a simple php array that looks like this & I am looping over it to assign its keys as properties to an stdClass object & its values as the values of those keys. My code looks like this
$arr = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$obj = new stdClass();
foreach ($arr as $key => $value) {
$obj->{$key} = $value;
}
After this point, my $obj looks like this after a print in the popular laravel php repl, tinker. Its just convinient for me to work in there
{#4867
+"one": 1,
+"two": 2,
+"three": 3,
+"four": 4,
+"five": 5,
}
A regular var_dump would look like
object(stdClass)#4867 (5) {
["one"]=>
int(1)
["two"]=>
int(2)
["three"]=>
int(3)
["four"]=>
int(4)
["five"]=>
int(5)
}
but that's no biggie, my main question is why can't i set these properties in an array_reduce using array_keys to get the key & using the array above to grab the value of that key like so;
$arr = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$obj = new stdClass();
$result = array_reduce(
array_keys($arr),
function ($carry, $curr) use ($arr) {
return $carry->{$curr} = $arr[$curr];
},
$obj
);
Trying to run this piece of code throws the error
Error Attempt to assign property "two" on int.
Am pretty sure am missing something because just passing an array with one element works, ie reducing ['one' => 1] using the same method produces an stdClass object with one property, one with a value of 1
Your array_reduce callback returns this expression:
return $carry->{$curr} = $arr[$curr];
But that does not return the object -- it is just the value that was assigned to one object property.
You'll want the callback to always return the carry (accumulator).
So have the callback do the assignment and then return the object:
$carry->{$curr} = $arr[$curr];
return $carry;

Cannot iterate over array after json_decode(file_get_contents(filename))

I want to write an Array as JSON into a file. Then i want to get the content, decode it and iterate over the array. The Problem is i cannot iterate over the Array that i get from the file. What am i doing wrong?
var_dump() shows the array.
<?php
$array = array(
array("Artikel" => "Bananen",
"Menge" => 10,
"id" => "4711"
),
array("Artikel" => "Eier",
"Menge" => 1,
"id" => "abc"
)
);
file_put_contents("daten.json", json_encode($array));
$array1 = json_decode(file_get_contents("daten.json"));
var_dump($array1);
for($i=0; $i<count($array1); $i++){
echo $array1[$i]["Menge"];
echo "<br>";
}
?>
If you run your code, you will get the error Cannot use object of type stdClass as array.
This is because when json_encode is executed, the nested arrays are interpreted as an objects.
If you write:
$array1 = json_decode(file_get_contents("daten.json"), true);
then the objects will be converted to arrays and everything will work as expected.

Extract all ids from array of objects

With PHP 7.4, I have associative array with objets :
$array = [
1 => Class {
'id' => 1,
'call' => true,
},
5 => Class {
'id' => 5,
'call' => false,
},
7 => Class {
'id' => 7,
'call' => true,
},
]
I want to extract all the IDs if the call attribute === true.
After searching, I think I should use the array_map function.
$ids = array_map(function($e) {
if (true === $e->call) {
return $e->id;
}
}, $array);
// Return :
array(3) {
[1]=> 1
[5]=> NULL
[7]=> 7
}
But I have two problems with this:
I don't want NULL results
I don't wish to have the associative keys in in my new array. I want a new array ([0=>1, 1=>7])
I know I can do it with a foreach() but I find it interesting to do it with a single PHP function (array_walk or array_map ?)
Create an array which is the call value indexed by the id and then filter it. As the id is the index, then extract the keys for the ids...
$ids = array_keys(array_filter(array_column($array, "call", "id")));
print_r($ids));
Array
(
[0] => 1
[1] => 7
)
Although I think a foreach() is a much more straight forward method.
You probably want array_filter to filter out what you don't want, then you can extract the id:
$ids = array_column(array_filter($array, function($e) {
return $e->call === true;
}), 'id');
You can reduce the array with a callback that conditionally adds each item's id to the "carry" array.
$ids = array_reduce($array, fn($c, $i) => $i->call ? [...$c, $i->id] : $c, []);

PHP getting values of the objects by key inside array

Hi all I have an array "$decodedData" of object from json data.
var_export($decodedData);
returns next:
array ( 0 => array ( 'number' => '2', 'type' => 'accs', ), 1 => array ( 'number' => '5', 'type' => 'accs', ), )
I'm trying to output all the "numbers" values:
foreach ($decodedData as $number)
{
echo implode(',', $number);
}
but I'm getting "type" values either
2,accs5,accs
How can I get rid of those?
You can use array_map to accomplish that.
The first parameter is a callback function that will receive each element and return something to replace it with. In this case, we are returning the number key of each element.
$result = array_map(function($val) {
return $val['number'];
}, $array);
echo implode(',', $result);
You're looping through an array of arrays, so $number is returning a complete array, not the number value. To access the number value of each, do something like this:
foreach ($decodedData as $number=>$val){
echo implode(',', $val['number']);
}

Best way to refer index which contains in array

In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?
Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.
You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);
You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation
Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.
There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.

Categories