Populate variable from required keys - php

$data variable get populated from required keys via $personalDetailsRequiredFields. The code below does work but is there a better shorter way?
$personalDetailsRequiredFields = [
'contact_title',
'contact_first_name',
'contact_last_name',
'contact_phone_number',
'contact_mobile_number',
'contact_email',
];
$personalDetails = SessionOrder::getPersonalDetails();
foreach($personalDetails as $key => $value) {
if (in_array($key,$personalDetailsRequiredFields)) {
$data['personalDetails'][$key] = $value;
}
}
echo "<pre>";
print_r($data);
echo "</pre>";

$data['personalDetails'] = array_intersect_key(
$personalDetails,
array_flip($personalDetailsRequiredFields)
);
should give you what you want without needing the loop and if test

Related

PHP split array into 2 arrays by value

I'm having a hard time figuring out how to implement this so here it is. I have an array
$arr = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1",
2=>"POD2",
),
"quantity_received"=>array(
0=>5,
1=>10,
2=>20
)
);
I want to split the arrays into two. Into something like this.
$pod_2 = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1"
),
"quantity_received"=>array(
0=>5,
1=>10
));
$pod_1 = array("purchase_order_details_id"=>array(
2=>"POD2"
),
"quantity_received"=>array(
2=>20
));
Anyone has an idea on how to do this ? Any thoughts is appreciated. Thanks
I use array_intersect to find the POs in a loop of unique POs.
Then I use array_inyersect_key to get the quantity.
This requires only one iteration per unique Purchase_order_detali_id.
Meaning it has a much better performance than looping the full array.
Edit: added extract to create the two variables. But I would rather keep them in the array if I was you.
$pods = array_unique($arr["purchase_order_details_id"]);
Foreach($pods as $pod){
$PO = array_intersect($arr["purchase_order_details_id"], [$pod]);
$qt = array_intersect_key($arr["quantity_received"], $PO);
$new[$pod] = ["purchase_order_details_id" => $PO, "quantity_received" => $qt];
}
Var_dump($new);
extract($new);
https://3v4l.org/dBpuJ
Try with below code:
$array = array();
foreach($arr['purchase_order_details_id'] as $key => $val)
{
$array[$val]['purchase_order_details_id'][] = $val;
$array[$val]['quantity_received'][] = $arr['quantity_received'][$key];
}
echo "<pre>";
print_r($array);
echo "</pre>";
extract($array);
echo "<pre>";
print_r($POD1);
echo "</pre>";
echo "<pre>";
print_r($POD2);
echo "</pre>";
foreach ($arr as $key => $val) {
$size = ceil(count($val) / 2);
$arr2 = array_chunk($val, $size, true);
$pod_2[$key] = $arr2[0];
$pod_1[$key] = $arr2[1];
}
var_dump($pod_2);
var_dump($pod_1);

How to echo value of "id"?

{"2b44928ae11fb9384c4cf38708677c48":{
"id":"115",
"qty":3,
"option":"{\"color\":{\"title\":\"Color\",
\"value\":\"\"
}
}",
"price":150,
"name":"Nightwear",
"shipping":"5",
"tax":3,
"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg",
"coupon":"",
"rowid":"2b44928ae11fb9384c4cf38708677c48",
"subtotal":450
}
}
Hello everyone,
This is my array and I want to echo value of only "id" i.e. I want to get value as '115' of key- "id". Please guide me how to make a foreach for this one? I have tried lots of variations but none worked :(
TIA :)
UPDATE-
I have tried this but did not get any result:
foreach($res as $k=>$t)
{
echo $t["product_details"]["id"];
}
Before you can use the JSON as an array you need to convert it first. use json_decode() for that.
<?php
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true);
foreach($array as $key=>$value){
echo $value['id'];
}
?>
Assuming you have an array of objects like you provided in your post, I have put your object in an array for testing
<?php
$json = '[{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}},'.
'{"2b44928ae11fb9384c4cf38708677c48":{"id":"116","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}]';
$json = json_decode($json);
foreach ($json as $object){
$propsArray = get_object_vars($object);
reset($propsArray);
echo $object->{key($propsArray)}->id . "<br>\n";
}
exit;
this outputs
115
116
try a live demo (https://eval.in/836364)
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true); // convert json string to array
$result = array_column($array, 'id'); // find matching array key and return values in array
foreach ($result as $value) { // echo each value with foreach loop
echo $id . '<br>';
}

PHP check variable if exists in array of json

Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';

How to use array with foreach in PHP

I'm try to using array in PHP by finding it index and keys as foreach.
example I want to get $k["ab"] or $ro["hh"] but I can't get it
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
var_dump($k);
}
?>
You'd better learn the structure of multi-dimensional array.
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $key => $values){
echo $key; // which will output "test", "ab", which are the array keys
print_r($values); // which will output the contents of the inner array (e.g. array("some"=>"d","hello"=>"e","ther"=>"a") )
// to obtain the inner array values, you can either use another foreach...
foreach($values as $k => $v) {
echo $k . ', ' . $v; // which will output "ad, tt", etc
}
// ...or specify which key to obtain
if(isset($values["ad"])) { echo $values["ad"]; }
// isset() must be used, as the key does not exist in 1st inner array
}
?>
Please try Below :
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
if($k == "ab"){
echo "<pre>";
print_R($ro);
echo 'HH Value ===> '.$ro['hh'];
}
}
?>
And Want to get All values and Keys Try Below For Each :
foreach($data as $k=>$ro){
foreach($ro as $inner_key => $inner_value){
echo "<br/> Key ===> ".$inner_key."==== value =====>".$inner_value;
}
}

Retrieving array keys from JSON input

I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC

Categories