Findind array in an associative array php - php

I am trying to search array values in key of associative array and then make and array of key values. I a using in_array() func to search but i can use foreach func for one array.
This is my code, but the issue is it asks me for string and I gave array.
function getrarity(){
$json = '{"cards":[
{
"card_verify_id":"1",
"name":"cardname1",
"rarity":"1"
},
{
"card_verify_id":"2",
"name":"cardname2",
"rarity":"2"
}]
}';
$card = array(1, 2);
$cards = json_decode($json);
$commons = array();
foreach($cards->cards as $items) {
if(in_array($card, $items->card_verify_id)){
$commons[] = array("$items->card_verify_id", "$items->name", "$items->rarity");
}
}
return $commons;
}
print_r(getrarity());

That's because in_array doesn't take an array as the first argument. You can simply filter and check if card_verify_id is in $card. Decoding as an array:
$cards = json_decode($json, true)['cards'];
$commons = array_filter($cards,
function($v) use($card) {
return in_array($v['card_verify_id'], $card);
});
Decoding as an object:
$cards = json_decode($json)->cards;
$commons = array_filter($cards,
function($v) use($card) {
return in_array($v->card_verify_id, $card);
});

Related

How to insert key value pair in an existing array object using php/laravel?

My Code:
$finalArray = json_encode($loanTypeCount);
Output:
[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]
Desired Output:
[{"name":"Salary","y":6, "selected": true},{"name":"Emergency","y":1, "selected": true}]
Inserted "selected": true key value pair. What is the way to do it in laravel/php?
If it's a Collection instance, you can do it with map()
$loanTypeCount->map(function($loan) {
$loan->selected = true;
return $loan;
});
Based on N69S' solution, here an example starting with a JSON encoded string instead of a collection instance and ending with a modified one.
$json = '[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]';
$arr = collect(json_decode($json, true))
->map(function ($item, $key) {
$item['selected'] = true;
return $item;
})
->toJson();
Simple solution with pure php:
$json = '[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]';
$obj=json_decode($json);
$obj[0]->selected = true;
$obj[1]->selected = true;
$newJson = json_encode($obj);
//[{"name":"Salary","y":"6","selected":true},{"name":"Emergency","y":"1","selected":true}]
Alternatively with foreach:
$json = '[{"name":"Salary","y":"6"},{"name":"Emergency","y":"1"}]';
foreach($obj=json_decode($json) as $key => $item){
$obj[$key]->selected = true;
}
$newJson = json_encode($obj);
//[{"name":"Salary","y":"6","selected":true},{"name":"Emergency","y":"1","selected":true}]

Array Search key and Replace value php

I have an array like
[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]
i have to json_decode it.
i want to change stok = 2 from detail "33,hitam".
but i'm seriously confused to use array search first and use array replace.
You could do it like this :
$stringarray = '[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]';
$array = json_decode($stringarray);
var_dump($array);
$replaced = replaceInObject($array, "detail", "33,hitam", "stok" , "2");
var_dump($replaced);
function replaceInObject($array, $field, $searchvalue, $valuefield, $newvalue){
foreach($array as $element){
if($element->$field == $searchvalue){
$element->$valuefield = $newvalue;
}
}
return $array;
}
You can use array_map to achieve this
$data = '[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]';
$json = json_decode($data, true);
$result = array_map(function($e) {
if ($e['detail'] == "33,hitam") $e['stok'] = "2";
return $e;
}, $json);

How to remove the arrays given in the arrows

$session_activity_category = array();
foreach($search_venue as $venue_b) {
$session_activity_category[] = $this->users_model->search_categories_by_session($venue_b->activity_venue_id);
}
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode(array('activity_category'=>$session_activity_category,'activity'=>$session_activity,'activity_session'=>$search_session,'activity_venue'=>$search_venue),JSON_UNESCAPED_SLASHES)
);
I want to remove the arrays given in the arrow lines
Convert the JSON to the array. Then just create a new array with the same key active category (in my example, something):
<?php
$json = '
{"something": [[
{
"blah": "blah"
},
{
"blah": "blah"
}
]]}
';
$array = json_decode($json, true);
$array = [
"something" => $array['something'][0],
];
echo json_encode($array);
Which will output:
{"something":[{"blah":"blah"},{"blah":"blah"}]}
Seems that $this->users_model->search_categories_by_session($venue_b->activity_venue_id) returns array of objects. You should parse this objects to the $session_activity_category array each iteration of search_categories_by_session function call.
$session_activity_category = array();
array_walk($search_venue, function($venue_b) use (&$session_activity_category) {
$categories = $this->users_model->search_categories_by_session($venue_b->activity_venue_id);
foreach ($categories as $category) {
$session_activity_category[] = $category;
}
});

How to Replace One Array index with another array in Php [duplicate]

This question already has answers here:
PHP array replace after matching value [duplicate]
(2 answers)
Closed 2 months ago.
Am using Php as my serverside scripting language.In my project I used Json string decoded into array.
My problem is how to overwrite the existing array index based on an array value.
my existing array looks like :
$array1 =[
{
"Name":"apple",
"color":"red",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
and the updated array content looks:
$upadatearray = [
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
}
];
I want to update the existing $array1 with new $upadatearray , bsed on the "Name" .If it is same then replace.
I want to look like:
$finalarray =[
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":
[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
I tried this :
for($j=0;$j<count($array1);$j++)
{
if($array1[$j]['Name'] == $upadatearray[0]['Name'])
$finalarray = array_replace($array1[$j],$upadatearray[0]);
}
But it will not work correctly.Is there any possible solution ?
Let you have this two arrays:
$array1 ='[{"Name":"apple","color":"red","property":[{"p1":"value1","p2":"value2"}]},{"Name":"Grape","color":"violet","property":[{"p1":"value1","p2":"value2"}]}]';
$upadatearray = '[{"Name":"apple", "color":"green", "property":[{"p1":"newvalue","p2":"newvalue2"}]}]';
$array1 = json_decode($array1, true);
$upadatearray = json_decode($upadatearray, true);
You can use array_replace function. But to make it replace items based on the Name column you should first make this column a key of array
function make_column_key($arr, $col_name) {
$keys = array_column($arr, $col_name);
$result = array_combine($keys, $arr);
return $result;
}
$array1 = make_column_key($array1, 'Name');
$upadatearray = make_column_key($upadatearray, 'Name');
And now simply use array_replace
$finalarray = array_replace($array1, $upadatearray);
If you don't need Name be the key of final array, you can get only values:
$finalarray = array_values($finalarray);
hi I think this code will help you.
//what i did is i created a final array variable which gets the value of old array.
$finalArray = $array1;
//then i perform a foreach loop for old array
foreach ($array1 as $key => $oldarray) {
//inside the updated array
foreach ($upadatearray as $key => $newarray) {
//if old array name and new array name is same replace content on the final array
if ($oldarray['Name'] == $newarray['Name']) {
$finalArray['Name'] = $newarray['Name'];
}
}
}

how to remove empty array value with key in php?

I am getting an array similar to the following one.
{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}
If form data values are null, I want to replace that key's value with the value of the next key.
Like above, after value 5, I have null values. It needs to be like this:
"final_data":["1","2","4","5","fill this with 6","remove this"]
"final_data":["1","2","4","5","6"] like this
I tried array_filter(), but it didn't help.
If the response is in json format then ...
$json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}';
$array = json_decode($json, TRUE);
foreach($array as $index => $a) {
$array[$index] = array_filter($a);
}
print_r($array);
https://eval.in/866379
Update:
foreach($array as $index => $a) {
$array[$index] = array_value(array_filter($a));
}
https://eval.in/866522
try following code,
foreach($myarray as $key=>$value)
{
if(is_null($value) || $value == '')
unset($myarray[$key]);
}
Try this array_filter() with array_map() and array_values()
<?php
$array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6"));
function filterMe($paraArr){
return array_values(array_filter($paraArr));
}
$array = array_map("filterMe",$array);
echo "<pre>";
print_r($array);
check the output here https://eval.in/866401

Categories