PHP: associate an array with another array both taken from curl - php

I have the following code that fetches arrays from a cURL.
$codici_hotel_arr = array();
foreach($data_destin['results'] as $key=>$val) {
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
$codici_definitivi = implode(', ', $codici_hotel_arr);
$codici_prezzi = implode(', ', $codici_price_arr);
The code returns these values:
**$codici_definitivi:**
"1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"
**$codici_prezzi**
"160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63".
I would need to get a $codici_prezzi for each $codici_definitivi.
As a response of a string cURL, both codes are as follows:
1074d0 -> 160.16;
19f726 -> 234.32;
1072ba -> 256.88;
etc...
It's possible?
Thank you

If I don't misunderstood your requirement then this should work. Remove extra imploding and try to array_combine() the two corresponding arrays.
// Your initial code, after removing imploding
$codici_hotel_arr = $codici_price_arr = [];
foreach($data_destin['results'] as $key=>$val) {
$codici_hotel_arr[] = '"' . $val['hotel_code'] . '"';
$codici_price_arr[] = '"' . $val['products'][0]['price'] . '"';
}
// I assume your array structure will be after looping curl response
$codici_hotel_arr = ["1074d0", "19f726", "1072ba", "183444", "1071bf", "112438", "1b326e", "15d8ab", "19d885", "193e61", "10aab2", "107155", "110669", "189b95", "16d78f", "18dd7d"];
$codici_price_arr = ["160.16", "234.32", "256.88", "325.42", "342.22", "353.30", "365.78", "372.84", "395.72", "478.75", "503.36", "543.39", "584.61", "584.61", "597.70", "601.63"];
$result = array_combine($codici_hotel_arr,$codici_price_arr);
print '<pre>';
print_r($result);
print '</pre>';
Result:
Array (
[1074d0] => 160.16
[19f726] => 234.32
[1072ba] => 256.88
[183444] => 325.42
[1071bf] => 342.22
[112438] => 353.30
[1b326e] => 365.78
[15d8ab] => 372.84
[19d885] => 395.72
[193e61] => 478.75
[10aab2] => 503.36
[107155] => 543.39
[110669] => 584.61
[189b95] => 584.61
[16d78f] => 597.70
[18dd7d] => 601.63
)
Edit: Because I don't understand your expected result that's why I post it also.If you want it on string format then try like this,
function print_string($v, $k) {
echo "$k->$v\n";
}
array_walk($result, "print_string");

Supposing that the indices of the arrays are aligned, I would do this:
<?php
for($i = 0; $i < count($codici_definitivi); $i++) {
echo $codici_definitivi[0] . ' -> ' . $codici_prezzi[0];
// or set up any other mapping you need, e.g. key => value in another array
}
?>
Edit: you should place this mapping before the implode statements, otherwise you overwrite the original arrays with strings.

$new_codici_prezzi = array();
if(count($codici_definitivi) === count($codici_prezzi)){
for($i = 0; $i < count($codici_definitivi); $i++){
$new_codici_prezzi[$codici_definitivi[$i]] = $codici_prezzi[$i];
}
}
//After that, $new_codici_prezzi is your new array.

Related

How to dynamically fill key and value in an associative array using for loop in PHP

$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);

Getting extra slashes while using JSON array in PHP

I am getting some extra slashes while making json array using PHP. My code is below.
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'reg_no' => $value['reg_no'],
'name' => $name,
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}
$result = array_values($result); // reindex result array
echo json_encode($result);exit;
?>
Here the json output is given below.
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]
Here my problem is I am adding $value['paper_code'].'/'.$value['subject']; and in output I am getting "BA001\/Mathematics". Here One extra slash(\) is added which I need to remove.
You can add JSON_UNESCAPED_SLASHES as the second parameter. LIke:
$result = array_values($result); // reindex result array
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;
This will result to:
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]
Doc: json_encode()

Get Specific Value From Json array in PHP

I'm Try To Access Some specific Value From Return JSON
Real Value is 79#45#597#10#10#10000#M
$retframe = str_ireplace('#',',', $stframe);
echo json_encode(array( 'Value' => $retframe));
///Output Response Back is
{"Value":"79,45,597,10,10,10000,M"}
I Want to Get Only Value of 79,597,10
If you need the 1st, 3rd and 5th number of $stframe
$stframe = '79#45#597#10#10#10000#M';
list($p1,$p2,$p3,$p4,$p5,$p6,$p7) = explode('#',$stframe);
$retframe = $p1 . ',' . $p3 . ',' . $p5;
echo json_encode(array( 'Value' => $retframe));
if you want to get 79,597,10 values statically than you will do it like this way.
$retframe = str_ireplace('#',',', $stframe);//$retframe = '79,45,597,10,10,10000,M';
$rs = explode(",",$retframe);
$array[] = $rs[0];
$array[] = $rs[2];
$array[] = $rs[3];
$array1= implode(",", $array);
echo json_encode(array( 'Value' => $array1));
and you will get result like this : {"Value":"79,597,10"}

Three dimension array

I'm trying to build a 3 dimension array with the following code :
while ($Inf = $queryPrep->fetch(PDO::FETCH_OBJ)) {
$cie_Names = array(
$Inf->dp_id=>array(
'name'=> $Inf->dp_desc,
'enabled'=>$Inf->dp_enabled));
}
Unfortunatly, this code was only returning the last record, so I chaged for :
$cie_Names = array();
while ($Inf = $queryPrep->fetch(PDO::FETCH_OBJ)) {
$cie_Names = [$Inf->dp_id]=>array(
'name'=> $Inf->dp_desc,
'enabled'=>$Inf->dp_enabled);
}
But now I'm getting a error.
I'll need to call my array later this way :
foreach ($depts as $ID => $DeptDetail) {
$optlist .= '<option value=' . $ID . '>' . $DeptDetail['name'] . $DeptDetail['enabled'] . '</option>';
}
You add a new element to an array by assigning to arrayName[]:
while ($Inf = $queryPrep->fetch(PDO::FETCH_OBJ)) {
$cie_Names[] = array(
$Inf->dp_id=>array(
'name'=> $Inf->dp_desc,
'enabled'=>$Inf->dp_enabled
)
);
}
However, this seems like a poor array layout -- each element of the cie_Names array will be an associative array with a different key; accessing them will be difficult because you won't know how the keys map to array indexes, you'll have to do a loop to find anything. What would probably be more useful is:
while ($Inf = $queryPrep->fetch(PDO::FETCH_OBJ)) {
$cie_Names[$Inf->dp_id] = array(
'name'=> $Inf->dp_desc,
'enabled'=>$Inf->dp_enabled
);
}
The keys of the cie_Names array will then by the dp_id values.

How to get values for each variable from this mysql cel result using php?

How to get each result from the below line using php?
ssrc=15012312307;themssrc=2790404163;lp=0;rxjitter=0.001079;rxcount=933;txjitter=0.000000;txcount=735;rlp=0;rtt=0.002000
I tried with explode and foreach but without success. Thanks!
Try following:
$str = "ssrc=15012312307;themssrc=2790404163;lp=0;rxjitter=0.001079;rxcount=933;txjitter=0.000000;txcount=735;rlp=0;rtt=0.002000";
$final_array = array();
$data_array = explode(';', $str);
foreach($data_array as $single_data)
{
$single_data = trim($single_data);
$single_unit = explode('=', $single_data);
$single_unit[0] = trim($single_unit[0]);
$single_unit[1] = trim($single_unit[1]);
$final_array[$single_unit[0]] = $single_unit[1];
}
print_r($final_array);
Here you will get array key as your variable name and array value as its value from cell.
$text = "ssrc=15012312307;themssrc=2790404163;lp=0;rxjitter=0.001079;rxcount=933;txjitter=0.000000;txcount=735;rlp=0;rtt=0.002000";
$exploded = explode(';', $text);
foreach($exploded as $data)
{
$temp = explode('=', $data);
$result .= 'Value of "' . $temp[0] . '" is: ' . $temp[1] . '<br>';
}
echo $result;
OUTPUT:
Value of "ssrc" is: 15012312307
Value of "themssrc" is: 2790404163
Value of "lp" is: 0
Value of "rxjitter" is: 0.001079
Value of "rxcount" is: 933
Value of "txjitter" is: 0.000000
Value of "txcount" is: 735
Value of "rlp" is: 0
Value of "rtt" is: 0.002000
You can edit this code inside foreach to your requirements. Eg. to array:
$result = Array();
foreach($exploded as $data)
{
$temp = explode('=', $data);
$result[$temp[0]] = $temp[1];
}
print_r($result);
OUTPUT:
Array
(
[ssrc] => 15012312307
[themssrc] => 2790404163
[lp] => 0
[rxjitter] => 0.001079
[rxcount] => 933
[txjitter] => 0.000000
[txcount] => 735
[rlp] => 0
[rtt] => 0.002000
)

Categories