Replace null with empty string value in multidimensional array php - php

I have one multidimensional array with null key value. How to replace null to empty string in multidimensional array php ? my array is
"result": [
{
"id": "1",
"first_name": "Kishan",
"last_name": "Patel",
"profile_picture": null,
"email": "imkishanpatel107#gmail.com",
"birthdate": "1992-07-10",
"gender": "male",
"nickname": "KK",
"town": null,
"state": "58",
"bio": "123",
"zipcode": "395006",
"radius": "12356",
"favroiteteam": "2",
"latitude": "1.25456",
"longitude": "4.5658787",
"message_enable": "0",
"ratting_enable": "0",
"add_friend_enable": "0",
"interested_in": null,
"user_sport": [
{
"sport": {
"id": "3",
"name": "Basketball",
"image": "",
"no_of_player": "9",
"is_active": "1"
},
"sportPosition": {
"id": "1",
"sport_id": "3",
"position_name": "Point Guard"
},
"skill_level": {
"id": "1",
"name": "Novice"
}
},
{
"sport": {
"id": "2",
"name": "Baseball",
"image": "",
"no_of_player": "10",
"is_active": "1"
},
"sportPosition": {
"id": "6",
"sport_id": "2",
"position_name": "Pitcher"
},
"skill_level": {
"id": "3",
"name": "Advanced"
}
},
{
"sport": {
"id": "8",
"name": "Roller Hockey",
"image": "",
"no_of_player": "0",
"is_active": "1"
},
"sportPosition": {
"id": "15",
"sport_id": "8",
"position_name": "Forward"
},
"skill_level": {
"id": "1",
"name": "Novice"
}
}
]
}
]

Simply put a loop and check if null with foreach
foreach ($array as $key => $value) {
if (is_null($value)) $array[$key] = "";
}

#Kishan Kikani you can not replace null to '' because both consider as empty value that in the output of your array there will be empty value at the place of null or '' you have to assign something to replace your value in above array like below you have both ways(your and mine) you can do:
<?php
$result = array("result"=>
array(
"id"=> "1",
"first_name"=> "Kishan",
"last_name"=> "Patel",
"profile_picture"=> null,
"email"=> "imkishanpatel107#gmail.com",
"birthdate"=> "1992-07-10",
"gender"=> "male",
"nickname"=> "KK",
"town"=> null,
"state"=> "58",
"bio"=> "123",
"zipcode"=> "395006",
"radius"=> "12356",
"favroiteteam"=> "2",
"latitude"=> "1.25456",
"longitude"=> "4.5658787",
"message_enable"=> "0",
"ratting_enable"=> "0",
"add_friend_enable"=> "0",
"interested_in"=> null,
"user_sport"=>
array(
"sport"=> array(
"id"=> "3",
"name"=> "Basketball",
"image"=> "",
"no_of_player"=> "9",
"is_active"=> "1"
),
"sportPosition"=> array(
"id"=> "1",
"sport_id"=> "3",
"position_name"=> "Point Guard"
),
"skill_level"=> array(
"id"=> "1",
"name"=> "Novice"
)
),
array(
"sport"=> array(
"id"=> "2",
"name"=> "Baseball",
"image"=> "",
"no_of_player"=> "10",
"is_active"=> "1"
),
"sportPosition"=> array(
"id"=> "6",
"sport_id"=> "2",
"position_name"=> "Pitcher"
),
"skill_level"=> array(
"id"=> "3",
"name"=> "Advanced"
)
),
array(
"sport"=> array(
"id"=> "8",
"name"=> "Roller Hockey",
"image"=> "",
"no_of_player"=> "0",
"is_active"=> "1"
),
"sportPosition"=> array(
"id"=> "15",
"sport_id"=> "8",
"position_name"=> "Forward"
),
"skill_level"=> array(
"id"=> "1",
"name"=> "Novice"
)
)
)
);
echo "<pre>";
print_r($result); // BEFORE
foreach($result as $rsKey => $rs){
foreach($rs as $key => $value){
if(is_null($value)){
$result[$rsKey][$key] = "";
}
}
}
echo "<pre>";
print_r($result); // after replace only null to "" but there will be a empty space in the values
foreach($result as $rsKey => $rs){
foreach($rs as $key => $value){
if(is_array($value)){
foreach ($value as $k => $v) {
foreach ($v as $k1 => $v1) {
if(empty($v1)){
$result[$rsKey][$key][$k][$k1] = "level2";
}
}
}
}
else{
if(is_null($value)){
$result[$rsKey][$key] = "level1";
}
}
}
}
echo "<pre>";
print_r($result); // after replace whole array empty values
try any one you want (y)

$arr = array(
"key1"=>"value1",
"key2"=>null,
"key3"=>array(
"subkey1"=>null,
"subkey2"=>"subvalue2"),
"key4"=>null);
echo json_encode(replace_null_with_empty_string($arr));
function replace_null_with_empty_string($array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
$array[$key] = replace_null_with_empty_string($value);
else
{
if (is_null($value))
$array[$key] = "";
}
}
return $array;
}

Piggybacking off #Atish's answer... I cleaned it up and made it simpler. This loops through the array and alters the value reference (&), then loops thru each next dimension of the array using recursion. #Daidon's answer only loops thru the first dimension.
The new function looks like this...
function null2empty($array){
foreach ($array as &$value) {
$value = (is_array($value)) ? null2empty($value) : $value;
$value = (is_null($value)) ? "" : $value;
}
return $array;
}
to use it, you would call it like this...
$profile_array = null2empty($profile_array);

Related

Insert value in array after every index using php

I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);

Creating nested JSON using PHP MySQL

I have an SQL Query returning certain fields, I am using json_encode() to get the data in JSON format, however I am having trouble getting it in the format I want.
PHP Code
<?php
function data() {
$runDistanceBasedOnCityQuery = "SELECT rc.id, rc.cityId, c.cityName, rc.runId, r.distance, rc.status FROM run_city rc INNER JOIN cities c ON c.id = rc.cityId INNER JOIN run_distance r ON r.id = rc.runId ORDER BY c.cityName";
$runDistanceBasedOnCityResult = $db->prepare($runDistanceBasedOnCityQuery);
$runDistanceBasedOnCityResult->bindParam(":cityId", $cityId, PDO::PARAM_INT);
$runDistanceBasedOnCityResult->execute();
$runDistanceBasedOnCityOutput = $runDistanceBasedOnCityResult->rowCount();
if ($runDistanceBasedOnCityOutput > 0) {
while ($runDistanceBasedOnCityRow = $runDistanceBasedOnCityResult->fetch(PDO::FETCH_ASSOC)) {
$array1 = array($runDistanceBasedOnCityRow['runId'], $runDistanceBasedOnCityRow['distance'], $runDistanceBasedOnCityRow['status']);
for ($i = 0; $i < sizeof($array1); $i++) {
$array2 = array("id" => $runDistanceBasedOnCityRow['id'], "runId" => $runDistanceBasedOnCityRow['cityId'], $runDistanceBasedOnCityRow['cityName'] => $array1);
}
$finalResultRunDistanceBasedOnCity[] = $array2;
}
$responseRunDistanceBasedOnCity = $finalResultRunDistanceBasedOnCity;
} else {
$responseRunDistanceBasedOnCity = 'Runs not found';
}
$result = array("status" => true,
"runsBasedOnCity" => $responseRunDistanceBasedOnCity
);
json($result);
}
function json($data) {
header('Content-Type:application/json');
if (is_array($data)) {
echo json_encode($data);
}
}
?>
The JSON format I am getting
"runsBasedOnCity": [
{
"id": "1",
"runId": "1",
"Bengaluru": [
"2",
"10k",
"1"
]
},
{
"id": "2",
"runId": "1",
"Bengaluru": [
"1",
"5k",
"1"
]
},
{
"id": "3",
"runId": "1",
"Bengaluru": [
"5",
"3k",
"0"
]
},
{
"id": "4",
"runId": "2",
"Chennai": [
"1",
"5k",
"1"
]
},
{
"id": "5",
"runId": "2",
"Chennai": [
"2",
"10k",
"1"
]
},
{
"id": "6",
"runId": "2",
"Chennai": [
"4",
"15k",
"1"
]
}
]
The Format I Require
"runsBasedOnCity": [
{
"id": "1",
"cityId": "1",
"Bengaluru":
[
{
runId : "2",
distance : "10k",
status : "1"
},
{
runId : "1",
distance: "5k",
status : "1"
},
{
runId : "5",
distance : "3k",
status : "0"
}
]
},
{
"id": "2",
"cityId": "2",
"Chennai":
[
{
runId : "1",
distance : "5k",
status : "1"
},
{
runId : "2",
distance: "10k",
status : "1"
},
{
runId : "4",
distance : "15k",
status : "1"
}
]
}
I am not able to figure out a better way of doing this, I am fairly new to this, do help me out. Thanks !
To efficiently group the subarray data, you should implement temporary keys. cityId is a suitable value to group by -- because cityNames may intentionally duplicate in the future but cityId must never un/intentionally duplicate in your database table.
When each new cityId is encountered, the conditional isset() call will determine whether a new/full set of data should be stored, or if data should merely be appended to the subarray.
I am calling array_slice() since it cuts down on unnecessary syntax / code-bloat.
After iterating through all of the rows, you can reindex the $result array, nest it inside runBasedOnCity, and add the status element.
I'll show my demo with PRETTY_PRINT so that it is easier to read, but in your actual code, you should remove the parameter. Also, a word of advice -- try to keep your variable names brief for improved readability.
Code: (Demo)
$resultset = [
["id" => "1", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "2", "distance" => "10k", "status" => "1"],
["id" => "2", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "1", "distance" => "5k", "status" => "1"],
["id" => "3", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "5", "distance" => "3k", "status" => "0"],
["id" => "4", "cityId" => "2", "cityName" => "Chennai", "runId" => "1", "distance" => "5k", "status" => "1"],
["id" => "5", "cityId" => "2", "cityName" => "Chennai", "runId" => "2", "distance" => "10k", "status" => "1"],
["id" => "6", "cityId" => "2", "cityName" => "Chennai", "runId" => "4", "distance" => "15k", "status" => "1"]
];
foreach ($resultset as $row) {
if (!isset($result[$row["cityId"]])) {
$result[$row["cityId"]] = array("id" => $row["id"], "cityId" => $row["cityId"], $row["cityName"] => array(array_slice($row,-3)));
} else {
$result[$row['cityId']][$row["cityName"]][] = array_slice($row,-3);
}
}
if (!isset($result)) { // don't need to check rowCount() at all
$result = 'Runs not found';
} else {
$result = array_values($result);
}
$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));
Output:
'{
"status": true,
"runsBasedOnCity": [
{
"id": "1",
"cityId": "1",
"Bengaluru": [
{
"runId": "2",
"distance": "10k",
"status": "1"
},
{
"runId": "1",
"distance": "5k",
"status": "1"
},
{
"runId": "5",
"distance": "3k",
"status": "0"
}
]
},
{
"id": "4",
"cityId": "2",
"Chennai": [
{
"runId": "1",
"distance": "5k",
"status": "1"
},
{
"runId": "2",
"distance": "10k",
"status": "1"
},
{
"runId": "4",
"distance": "15k",
"status": "1"
}
]
}
]
}'
After explaining how you wanted to preserve the id values in the subarrays, here is that solution:
Code: (Demo)
foreach ($resultset as $row) {
if (!isset($result[$row["cityId"]])) {
$result[$row["cityId"]] = array("cityId" => $row["cityId"], $row["cityName"] => array(array("id" => $row["id"])+array_slice($row,-3)));
} else {
$result[$row['cityId']][$row["cityName"]][] = array("id" => $row["id"])+array_slice($row,-3);
}
}
if (!isset($result)) { // don't need to check rowCount() at all
$result = 'Runs not found';
} else {
$result = array_values($result);
}
$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));

PHP - Moving a key within an array and flatten it

I have this array of object:
[
{
"id": 1,
"name": "Carbo",
"menus": [
{
"id": 33,
"name": "FloralWhite",
"image": {
"web": "https://lorempixel.com/640/360/food/?89722",
"mobile": "https://lorempixel.com/640/360/food/?89722",
"square": "https://lorempixel.com/640/360/food/?89722"
},
"logs": {
"price": 2
}
},
{
"id": 40,
"name": "LightGray",
"image": {
"web": "https://lorempixel.com/640/360/food/?63930",
"mobile": "https://lorempixel.com/640/360/food/?63930",
"square": "https://lorempixel.com/640/360/food/?63930"
},
"logs": {
"price": 2
}
},
]
}
]
What I want to achieve:
[
{
"id": 1,
"name": "Carbo",
"menus": [
{
"id": 33,
"name": "FloralWhite",
"image": {
"web": "https://lorempixel.com/640/360/food/?89722",
"mobile": "https://lorempixel.com/640/360/food/?89722",
"square": "https://lorempixel.com/640/360/food/?89722"
},
"price": 2
},
{
"id": 40,
"name": "LightGray",
"image": {
"web": "https://lorempixel.com/640/360/food/?63930",
"mobile": "https://lorempixel.com/640/360/food/?63930",
"square": "https://lorempixel.com/640/360/food/?63930"
},
"price": 2
},
]
}
]
I've tried using laravel collection flatten with depth but it fail
$data = collect($data->menus);
$data = $data->flatten(1);
$data->values()->all();
How can I flatten the menus['logs'] object so it can one level with menu?
Something like this should do the trick. Simply iterate over your array, set the new property and remove the one you don't want.
$data = json_decode("[{
\"id\": 1,
\"name\": \"Carbo\",
\"menus\": [
{
\"id\": 33,
\"name\": \"FloralWhite\",
\"image\": {
\"web\": \"https://lorempixel.com/640/360/food/?89722\",
\"mobile\": \"https://lorempixel.com/640/360/food/?89722\",
\"square\": \"https://lorempixel.com/640/360/food/?89722\"
},
\"logs\": {
\"price\": 2
}
},
{
\"id\": 40,
\"name\": \"LightGray\",
\"image\": {
\"web\": \"https://lorempixel.com/640/360/food/?63930\",
\"mobile\": \"https://lorempixel.com/640/360/food/?63930\",
\"square\": \"https://lorempixel.com/640/360/food/?63930\"
},
\"logs\": {
\"price\": 2
}
}
]
}]");
foreach($data as $val){
foreach($val->menus as $menuVal){
$menuVal->price = $menuVal->logs->price;
unset($menuVal->logs);
}
}
#Stefen Suhat i really don't know what is the syntax for laravel but i did it with a simple php foreach() hope this will help you, as your array's depth is long so i had gone to all the levels of your array, check code and output snippet here https://eval.in/806879
try below one:
<?php
$array = array(
array(
"id"=> 1,
"name"=> "Carbo",
"menus"=> array(
array(
"id"=> 33,
"name"=> "FloralWhite",
"image"=> array(
"web"=> "https=>//lorempixel.com/640/360/food/?89722",
"mobile"=> "https=>//lorempixel.com/640/360/food/?89722",
"square"=> "https=>//lorempixel.com/640/360/food/?89722"
),
"logs"=> array(
"price"=> 2
)
),
array(
"id"=> 40,
"name"=> "LightGray",
"image"=> array(
"web"=> "https=>//lorempixel.com/640/360/food/?63930",
"mobile"=> "https=>//lorempixel.com/640/360/food/?63930",
"square"=> "https=>//lorempixel.com/640/360/food/?63930"
),
"logs"=> array(
"price"=> 2
)
),
)
)
);
foreach($array as $key => $value){
foreach ($value as $key1 => $value1) {
if(is_array($value1) && $key1 == "menus"){
foreach($value1 as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
if(is_array($value3) && $key3 == "logs"){
unset($array[$key][$key1][$key2][$key3]);
$array[$key][$key1][$key2] = array_merge($array[$key][$key1][$key2], $value3);
}
}
}
}
}
}
echo "array after<br>";
echo "<pre>";
print_r($array); //your array after
?>

How to merge two JSON under an Array in PHP

I get details from the user through HTML form, and onclick the form submission, I run the php file, save2json.php, which retrieves from HTML form, and posts it as JSON in the file appointments.json.
save2json.php
$formdata = array(
$_POST['doctor'] => array(
'name'=> $_POST['name'],
'phone'=> $_POST['phone'],
'bday'=> $_POST['bday'],
'datepicker'=> $_POST['datepicker'],
)
);
$filetxt = 'appointments.json';
$arr_data = array();
if(file_exists($filetxt))
{
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
if(file_put_contents('appointments.json', $jsondata))
What I get: [appointments.json]
[{
"Doctor #3": {
"name": "0",
"phone": "0",
"bday": "0",
"datepicker": "0"
}
}, {
"Doctor #3": {
"name": "1",
"phone": "1",
"bday": "1",
"datepicker": "1"
}
}, {
"Doctor #1": {
"name": "2",
"phone": "2",
"bday": "2",
"datepicker": "2"
}
}, {
"Doctor #2": {
"name": "3",
"phone": "3",
"bday": "3",
"datepicker": "3"
}
}]
What I want: [appointments.json]
[{
"Doctor #3": [{
"name": "0",
"phone": "0",
"bday": "0",
"datepicker": "0"
},
{
"name": "1",
"phone": "1",
"bday": "1",
"datepicker": "1"
}
],
"Doctor #1": {
"name": "2",
"phone": "2",
"bday": "2",
"datepicker": "2"
},
"Doctor #2": {
"name": "3",
"phone": "3",
"bday": "3",
"datepicker": "3"
}
}]
If it is under same doctor, I want to make both objects come under the same array. And if it isn't like Doctor 1 and Doctor 2, in this case, I want them as separate apart from Doctor 3 array.
Thanks in Advance :)
This is the first attempt to put it inside the doctor array key:
<?php
// build the array
$docDetails = array(
'name'=> $_POST['name'],
'phone'=> $_POST['phone'],
'bday'=> $_POST['bday'],
'datepicker'=> $_POST['datepicker'],
);
// get the file's content as an array.
$filetxt = 'appointments.json';
if(file_exists($filetxt))
$arr_data = json_decode(file_get_contents($filetxt), true);
else
$arr_data = array();
$arr_data[$_POST['doctor']][] = $docDetails;
?>

combine array if any value is found duplicates php

I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and out put the results. For example, given the following array:
Original Array:
Array
{
"OrderId": "1",
"ProductOrderedId": "1",
"CallerId": "1",
},
{
"OrderId": "2",
"ProductOrderedId": "2",
"CallerId": "2",
},
{
"OrderId": "2",
"ProductOrderedId": "3",
"CallerId": "2",
}
}
Expected Result:
Array
{
"OrderId": "1",
"ProductOrderedId": "1",
"CallerId": "1",
},
{
"OrderId": "2",
"ProductOrderedId": "2,3",
"CallerId": "2",
}
}
try this code hope this helpful for you.
$newArrayData = array();
$valuesProduct = array();
foreach ($fetchData as $key => $value) {
if (count($value) > 1) {
foreach ($value as $keys => $vals) {
$valuesProduct[] = $vals['ProductOrderedId'];
}
$implodeVal=implode(',',$valuesProduct);
$newArrayData[]= array('OrderId' => $value[0]['OrderId'], 'CallerId' => $value[0]['CallerId'],
"ProductOrderedId" => $implodeVal);
} else {
$newArrayData[]=array('OrderId' => $value[0]['OrderId'], 'CallerId' => $value[0]['CallerId'],
"ProductOrderedId" => $value[0]['ProductOrderedId']);
}
}
print_r($newArrayData);
you also can use this if you find it simple.
$values = array(
array(
"OrderId"=> "1",
"ProductOrderedId"=> "1",
"CallerId"=> "1",
),
array(
"OrderId"=> "4",
"ProductOrderedId"=> "2",
"CallerId"=> "2",
),
array(
"OrderId"=> "4",
"ProductOrderedId"=> "3",
"CallerId"=> "2",
)
);
$temp=array();
foreach ($values as $value) {
if(isset($temp[$value["OrderId"]])){
$temp[$value["OrderId"]]["ProductOrderedId"]=$temp[$value["OrderId"]]["ProductOrderedId"].",".$value["ProductOrderedId"];
}else{
$temp[$value["OrderId"]]=$value;
}
}
$final_array= array_values($temp);

Categories