I have this object in my session
name: "test",
is_feature: "0",
attributes: [
{
'5': "blue"
},
{
'7': "iOS"
}
],
cost: "2000",
I want to use attributes in foreach.some thing like below code:
foreach ($product->attributes as $attribute){
ProductAttributeValue::create([
'attribute_id' => $attribute->key, //like 5,7
'value' => $attribute->value //like blue,iOS
]);
}
Try this loop:
First you convert json to associative arrays like:
$productAttributes = json_decode($product->attributes, true);
and then
foreach ($productAttributes as $attributes) {
foreach ($attributes as $key => $attribute) {
ProductAttributeValue::create([
'attribute_id' => $key, // like 5,7
'value' => $attribute // like blue,iOS
]);
}
}
I hope it would helpful.
You use this:
$str = '{"name": "test", "is_feature": "0", "attributes": [{"5": "blue"},{"7": "iOS"}],"cost": "2000"}';
$arr = json_decode($str, true); // convert the string to associative array
foreach($arr["attributes"] as $attribute) {
$key = key($attribute); // get the first key as "5" of "7"
echo "key: $key and val: " . $attribute[$key]; // access the value as $attribute[$key] will give blue or ios
};
Live example: 3v4l
Reference: key
Here is a solution for you.
$strArr = [
'name'=>"test",
'is_feature'=> "0",
'attributes'=>[[5=> "blue"],[7=> "iOS"]],
'cost'=> "2000"
];
$str = json_encode($strArr);
$arr = (array) json_decode($str);
$att = (array) $arr['attributes'];
foreach($att as $val) {
foreach($val as $key=>$attributes) {
echo "key: ".$key." and val: " . $attributes . PHP_EOL;
}
};
Output:
key: 5 and val: blue
key: 7 and val: iOS
Hope this will help you
Related
I have an array similiar to the one below:
array("animal" => array("lion", "fish", "tiger)
And I want to turn into the following in JSON format.
'{"group":"animal","types":["lion", "fish", "tiger"]}'
How do I add the 'labels' such as "group" and "type"?
$array=array();
$array['animal'] = array('lion','tiger','fish');//Your array
echo json_encode(array("group"=>"animal","types"=>$array['animal']));
//Output : {"group":"animal","types":["lion","tiger","fish"]}
Create and format a result array that will allow you to store the datas in the expected format.
<?php
$arr = array("animal" => array("lion", "fish", "tiger"));
$result = array("group" => "",
"types" => array());
foreach ($arr as $key => $value)
{
$result["group"] = $key;
$result["types"] = $value;
}
var_dump(json_encode($result));
output :
string(50) "{"group":"animal","types":["lion","fish","tiger"]}"
If you have many groups, the loop might need to be changed a bit :
<?php
$arr = array(array("animal" => array("lion", "fish", "tiger")),
array("colors" => array("red", "green", "blue")));
$finalResult = array();
foreach ($arr as $item)
{
foreach ($item as $key => $value)
{
$result["group"] = $key;
$result["types"] = $value;
$finalResult[] = $result;
}
}
var_dump(json_encode($finalResult));
Output :
string(102) "[{"group":"animal","types":["lion","fish","tiger"]},{"group":"colors","types":["red","green","blue"]}]"
I would like to Loop throught services but I don't know the index name. They come randomly, example I got 8 and 9 but I do not know them.
"2": {
"first_name": "khalfan",
"last_name": "mussa",
"date": "2017-06-06 09:21:36",
"gender": "male",
"services": {
"8": {
"name": "See a Doctor",
"results": ""
},
"9": {
"name": "Kichocho",
"results": "FD- 73"
}
}
},
From #Alive to Die answer, I made some changes and I think this code will loop in your services no matter the index.
$array = json_decode($json, true);
foreach ($array as $values) {
foreach ($values as $keys => $value) {
if (is_array($value)) {
foreach ($value as $key => $val) {
if (is_array($val)) {
foreach ($val as $k => $v) {
echo $k . ":" . $v . "\n";
}
}
}
}
}
}
Suppose you have json stored in $json variable.
$json = json_decode($json);
foreach($json as $entry) {
foreach($entry['services'] as $services) {
//$services['name']
//and other data here
}
}
You don't need to know the index while using foreach but you can get index from it.
The following are four available options:
<?php
$arr = ["2" => [
["first_name"=> "khalfan",
"last_name"=> "mussa",
"date"=>"2017-06-06 09:21:36",
"gender"=> "male"],
["services" =>
["8" => ["name" => "See a Doctor","results"=> ""],
"9" => ["name"=> "Kichocho","results"=> "FD- 73"]
]
]
]];
for ($i=0, $max=count($arr["2"]); $i < $max; $i++) {
if ( isset( $arr["2"][$i]["services"])) {
$a = $arr["2"][$i]["services"];
foreach($a as $e) {
echo $e["name"],"\t";
echo $e["results"],"\n";
}
}
continue;
}
See live code
The advantage here is that the code does work with a foreach as per the OP's request. But the code is involved and not as fast as it could be, owing to that if conditional.
Another solution that is faster:
<?php
$arr = ["2" => [
["first_name"=> "khalfan",
"last_name"=> "mussa",
"date"=>"2017-06-06 09:21:36",
"gender"=> "male"],
["services" =>
["8" => ["name" => "See a Doctor","results"=> ""],
"9" => ["name"=> "Kichocho","results"=> "FD- 73"]
]
]
]];
$count = count($arr["2"]);
$last = $count - 1; // b/c of zero-based indexing
foreach ($arr as $e) {
foreach($e[$last]["services"] as $a) {
echo $a["name"],"\t";
echo $a["results"],"\n";
}
}
// Or an easier solution without resorting to foreach:
array_walk_recursive($arr,function($item,$key) {
if ($key == "name") echo $item,"\t";
if ($key == "results") echo $item,"\n";
});
See live code
Whether $arr["2"] contains two elements or more as long as the last one is the "services" associate array, this foreach code works. But, this type of "array walk" can best be carried out with a built-in function designed for this very purpose, array_walk_recursive. With this function, you don't have to worry about how to construct the perfect foreach; the iteration occurs behind the scenes and all you need is to supply a callback. array_walk_recursive will drill down to the "services" element and if there is one or more associative arrays with keys of "name" and "results", then their respective values display.
The fourth possibility is one of those "why would you" situations. Why take an array and json_encode it and then json_decode it back to an array and then apply array_walk_recursive? But, the code does work:
<?php
$arr = ["2" => [
["first_name"=> "khalfan",
"last_name"=> "mussa",
"date"=>"2017-06-06 09:21:36",
"gender"=> "male"],
["services" =>
["8" => ["name" => "See a Doctor","results"=> ""],
"9" => ["name"=> "Kichocho","results"=> "FD- 73"]
]
]
]];
$result=json_decode(json_encode($arr),true);
array_walk_recursive($result, function($value,$key){
if ($key == "name" ) { echo $value,"\t";}
if ($key == "results") { echo $value,"\n";}
});
See live code
Im trying to build a json array in php with this structure:
[{"id":"name last name",
"id":"name last name",
"id":"name last name"
}]
where the id key is always a different number, not only id string
Im trying to do this:
for ($i = 0; $i < count($array); $i++){
//$namesArray[] = array($array[$i]["id"] =>$array[$i]["name"].
// " ".$array[$i]["last"]." ".$array[$i]["name"]);
$namesArray[] = array_fill_keys(
$array[$i]["id"],
$array[$i]["name"]." ".
$array[$i]["last"]." ".
$array[$i]["name"]
);
}
echo json_encode($namesArray);
With the commented lines I get something like this:
[{"id":"name last name"},
{"id":"name last name"}
]
But I dont want that, I want all keys and values in a single array.
Thanks.
Keep your code clean
$array = [];
$array[] = ['id'=>3 , 'name'=>'H', 'last'=>'bensiali' ];
$array[] = ['id'=>4 , 'name'=>'Simon', 'last'=>'Says' ];
$array[] = ['id'=>5 , 'name'=>'Mohammed', 'last'=>'Ali' ];
$val = [];
foreach ($array as $key => $value) {
$val[$value['id']] = sprintf("%s %s" , $value['name'] , $value['last']);
}
echo json_encode($val);
And output will be:
{"3":"H bensiali","4":"Simon Says","5":"Mohammed Ali"}
Here is how you can do it:
// sample data
$array = array(
array("id" => 1, "name" => "James", "last" => "Last"),
array("id" => 2, "name" => "Micheal", "last" => "Jackson"),
);
// create empty object (associative array)
$obj = (object) array();
// add key/value pairs to that object
foreach ($array as $row) {
$obj->$row["id"] = $row["name"] . " " . $row["last"];
}
// wrap object in a single-element array
$result = array($obj);
// output to JSON string
echo json_encode($result, JSON_PRETTY_PRINT);
Output:
[
{
"1": "James Last",
"2": "Micheal Jackson"
}
]
You can use functional approach to fill desired array with array_reduce:
$array = [
['id' => 1, 'name' => 'name1', 'last' => 'last1'],
['id' => 2, 'name' => 'name2', 'last' => 'last2'],
['id' => 3, 'name' => 'name3', 'last' => 'last3'],
];
$newArray = array_reduce($array, function($carry, $item) {
$carry[$item['id']] = $item["name"]." ".
$item["last"]." ".
$item["name"];
return $carry;
});
var_dump($newArray);
And output will be:
array(3) {
[1]=>
string(17) "name1 last1 name1"
[2]=>
string(17) "name2 last2 name2"
[3]=>
string(17) "name3 last3 name3"
}
How to convert this array:
$array = [
"order" => [
"items" => [
"6" => [
"ndc" => "This value should not be blank."
],
"7" => [
"ndc" => "This value should not be blank."
]
]
]
];
to
$array = [
"order[items][6][ndc]" => "This value should not be blank.",
"order[items][7][ndc]" => "This value should not be blank.",
];
First array may have unlimited number of nested levels. So nested foreach is not an option.
I spent a lot of time searching for the solution and got nothing. Can, please, someone help or guide me?
Something like this should do the job :
$newArr = [];
function reduce_multi_arr($array, &$newArr, $keys = '') {
if (!is_array($array)) {
$newArr[$keys] = $array;
} else {
foreach ($array as $key => $val) {
if ($keys === '') $nextKey = $key; // first key
else $nextKey = '[' . $key . ']'; // next [keys]
reduce_multi_arr($val, $newArr, $keys . $nextKey);
}
}
}
reduce_multi_arr($array, $newArr);
print_r($newArr);
Output :
Array
(
[order[items][6][ndc]] => 'This value should not be blank.'
[order[items][7][ndc]] => 'This value should not be blank.'
)
When a form gets posted, I get some checkbox values like the below:
Array ( [chk0] => true ,
[chk1] => true,
[chk3] => true,
[chk1002] => on,
[chk1005] => on
)
Using PHP,How can I construct a JSON request like this by using the above variables?
"data":
[
{
"checkboxval": true,
"id": 0
},
{
"checkboxval": true,
"id": 1
},
{
"checkboxval": true,
"id": 3
},
{
"checkboxval": true,
"id": 1002
},
{
"checkboxval": true,
"id": 1005
}
]
Please note that my POST variables can have other form variables too, but all checkbox values will be named with the prefix "chk"
$output = array();
foreach ($input as $k => $v) {
$output[] = array(
'checkboxval' => !!$v,
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
foreach ($_POST as $k => $v) {
$output[] = array(
'checkboxval' => ($v=='on'? true : ($v=='off' ? false : !!$v)),
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
Credits to cletus who provided the basis for this code.
Have a look at the json_encode() php function. You'll have to massage your array a little to get the exact JSON format you're after.
Heres an example...
$_POST["chk1"] = "Hello";
$_POST["chk2"] = "World";
$jsonArray = array();
foreach($_POST as $key => $val){
if(preg_match("/chk/", $key)){
$jsonArray[$key] = $val;
}
}
$jsonArray = array("Data" => $jsonArray);
$json = json_encode($jsonArray);
echo "<pre>";
echo $json;
echo "</pre>";
Outputs this:
{"Data":{"chk1":"Hello","chk2":"World"}}
I haven't tested this yet, but maybe something like this:
$json = '"data": [';
$first = true;
foreach ($_POST as $k => $v){
if (preg_match('/^chk(\d+)$/', $k, $m)){
if ($first) $first = false; else $json .= ", ";
$json .= sprintf('{ "checkboxval" : %s, "id" : %s }', ($v && $v != "off") ? "true" : "false", $m[1]);
}
}
$json .= ']';