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.
Related
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()
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.
I have the following PHP code:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
I want to be able to get the second value in a nested array by identifying a first. eg: if_exists("Donald") would return "trump".
I've tried to recurse through the array but I'm at a loss on how to select the second value once the first is identified.
Any help would be appreciated
You can use something like this:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
$search_val = "Donald";
$key = array_search($search_val, array_column($special_files,0));
$output = $special_files[$key][1]; //outputs "Trump"
Here is a working sample.
Well, you can try the following:
foreach ($special_files as $special_file) {
$i = 1;
foreach ($special_file as $element) {
if ($i==2) {
echo ("Second value is: " . $element);
break;
}
$i++;
}
}
You can extract the [1] elements and index them by the [0] elements:
$lookup = array_column($special_files, 1, 0);
$result = isset($lookup['Donald']) ?: false;
The $lookup array yields:
Array
(
[Turnip] => Tweed
[Donald] => Trump
)
I am currently learning PHP and I am stuck with this problem while testing foreach with multi-dimensional arrays.
Here is my array:
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
Whenever I try to output I always get an error of Array to string conversion or Invalid argument. Can somebody tell me how could I correctly output this multi-dimensional array using foreach?
If I do it this way, the data like 125,000, basically the value assigned to age and salary isn't written out.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
If I do it this way, then it writes out, but as well it writes out "Array" and array to string error:
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.$values.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
Thanks.
Try following code
<?php
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
foreach( $employees as $names_of_employees => $data ){
echo $names_of_employees.'<br>';
echo "Salary: ".$data['salary'].'<br>';
echo "Age: ".$data['age'].'<br>';
if( isset($data['hobbies']) && !empty($data['hobbies']) ) {
echo "Hobbies: ";
foreach( $data['hobbies'] as $hobbies ) {
echo $hobbies.'<br>';
}
}
}
Well, it depends on what you want.
foreach( $employees as $name => $data ){
echo $name;
echo $data['age'];
echo $data['salary'];
// ...etc...
}
It looks like for array element 'John' you've got an extra item in the second dimension. I believe this is ok in PHP but perhaps you have to account for this in the code you use to read the values out.
It is because you are trying to convert an array to a string. The problem is caused by hobbies since it is an array. So in your foreach loop that goes through $data you need to check if it is an array or if the key is equal to hobbies.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
if(is_array($values)) { //or you could say if($specifics == 'hobbies')
echo $specifics . ': ' . implode(',',$values) . '<br>';
} else {
echo $specifics . ': ' . $values . '<br>';
}
}
}
Is there anyway to loop through an array and insert each instance into another array?
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
foreach($aCartInfo['items'] as $item){
'x_line_item' => $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N',
}
);
Not directly in the array declaration, but you could do the following:
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item){
$aFormData['x_line_item'][] = $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N';
}
Yes, there is a way ; but you must go in two steps :
First, create your array with the static data
And, then, dynamically add more data
In your case, you'd use something like this, I suppose :
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(), // right now, initialize this item to an empty array
);
foreach($aCartInfo['items'] as $item){
// Add the dynamic value based on the current item
// at the end of $aFormData['x_line_item']
$aFormData['x_line_item'][] = $item['id'] . '<|>' . $item['title'] . '<|>' . $item['description'] . '<|>' . $item['quantity'] . '<|>' . $item['price'] . '<|>N';
}
And, of course, you should read the section of the manual that deals with arrays : it'll probably help you a lot ;-)
You mean something like this :
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item) {
$aFormData['x_line_item'][] = implode('<|>', $aCartInfo['items']).'<|>N',
}