php array make one value as key and second as value [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Below is my array I have to convert first value as key and second as value,
Array
(
[0] => Array
(
[region_code] => AB
[region_name] => Alberta
)
)
Please suggest best solutions.I am using array map but its not working.

You can use array_column(), demo
[(PHP 5 >= 5.5.0, PHP 7)] refer to Call to undefined function array_column()
array_column($array, 'region_name', 'region_code');
for older version of php
foreach ($array as $v) {
$result[$v['region_code']] = $v['region_name'];
}

try it out.
$arr = Array(0 => Array('region_code' => 'AB','region_name' => 'Alberta'));
print_r(array_column($arr, 'region_name', 'region_code'));

Related

Array in php formarting [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I’m having issues with an array in PHP. I create an array, it’s good, but in order to see it I use json_encode. See examples below.
Original array:
Array (
[0] => Array ( [0] => GCXO )
[1] => Array ( [0] => LEAS )
[2] => Array ( [0] => LECO )
)
I get this:
[["GCXO"],["LEAS"],["LECO"]]
I want this:
["GCXO", "LEAS", "LECO"]
The problem is that if I don’t use json_encode it returns the word array.
Does anyone knows how to get that result?
If the JSON shows [["GCXO"],["LEAS"],["LECO"]] then you have a multi-dimensional array and need to flatten it to get ["GCXO", "LEAS", "LECO"]:
echo json_encode(array_merge(...$array));
When you use json_encode, you are in fact converting the array to a JSON object, its not longer an "array".
If you only want to see the content of the array, you can use:
print_r($array)
or, you can format it as you like with a loop accessing it values with $array[iterator]
Also you can iterate trough it with foreach, giving it the format that you need.
foreach($array as $object){
echo ','.$object;
}
for example
use function implode(',', $array);
https://www.php.net/manual/en/function.implode.php

Nested Json Array into Mysql with PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is my first time working with json, just playing around with some data.
This is part of my json
Array
(
[DataSet] => Array
(
[Table] => Array
(
[0] => Array
(
[Driver] => John Doe
[Shift Date] => 2018-01-05T00:00:00-05:00
I want to be able to get all the [Driver] and [Shift Date] fields and put them into a table. It has 2 columns Driver and ShiftDate, not sure where I go from here.
After lots of googling I have come up with the solution, and I apologize if I didn't word my question right this is my first crack at this, but I figured posting the answer may help someone else trying to figure this out:
$str = file_get_contents('./cgapi.json');
$json = json_decode($str, true);
foreach($json['DataSet']['Table'] as $item) {
$stmt = $dbcon->prepare("INSERT INTO DriverData (DriverName, ShiftDate, Minutes, Stops, Gallons) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $item['Driver'], $item['Shift Date'], $item['Minutes'], $item['Stops'], $item['Gallons']);
$stmt->execute();
$stmt->close();
}
$drivers = array_column('Driver', $yourData);
$dates = array_column('Shift Date', $yourData);
Array column extracts all the values of the key provided as the first argument.
http://php.net/manual/en/function.array-column.php

PHP Vertical String to Horizontal String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i got the result my for loop :
FFFF
AAAA
TTTT
EEEE
while mod=4 my loop echo br
but i want result like this :
FATE
FATE
FATE
FATE
how i do this in php ?
thanks for answers and sorry my english:D
This is almost a duplicate of:
How to restructure multi-dimensional array with columns as rows? and
Combining array inside multidimensional array with same key
This can be done with foreach loops, but I like the condensed variadic method (PHP 5.6+).
You can research the aforementioned links to see the other techniques if your version isn't high enough or you want something different.
The strings just need to be converted to arrays before rotating, then imploded() after rotating.
Code: (Demo)
$input=['FFFF','AAAA','TTTT','EEEE'];
$rotated=array_map(function(){return implode(func_get_args());},...array_map('str_split',$input));
var_export($rotated);
Output:
array (
0 => 'FATE',
1 => 'FATE',
2 => 'FATE',
3 => 'FATE',
)
Here is a less fancy method to achieve the same result:
$input=['FFFF','AAAA','TTTT','EEEE'];
$length=strlen($input[0]);
foreach($input as $string){
for($offset=0; $offset<$length; ++$offset){
if(!isset($rotated[$offset])){$rotated[$offset]='';}
$rotated[$offset].=$string[$offset];
}
}
var_export($rotated);

Insert a variable in blank array that variable contains array key and value [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My variable which retrieve from database is:
$MyVariable="1=>'raju',2=>'rana',3=>'keya',4=>'muaz',5=>'',6=>'Asif'";
My array will be:
$MyArray=array($MyVariable);
Now I want to print a value using a key. Like:
echo $MyArray[2];
My output should be:
rana
But output is nothing!
eval() has security implications, but that's how this string of partial crap is turned into an actual array:
eval('$MyArray = array('.$MyVariable.');');
print_r($MyArray);
You should really store each value as a related row in another table instead of array data.
Your variable $myVariable is a string consisting of array keys.
If you were to write it as an array, it would work without problems:
$myvariable = array(
1 => 'raju',
2 => 'rana',
3 => 'keya'
// More entries
);
If this is the output of a function, you may want to make that function output JSON instead, as that is parseable to an array with just one json_decode call.
If you still want to parse this, you'll have to do some more advanced string parsing:
$data = array();
$bits = preg_match_callback("/(\d+)=>'(.*?)'(\,)?/", function($matches) use ($data){
$data[$matches[1]] = $matches[2];
}, $MyVariable);

How to remove some part of text in the first index of php array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is my array in php
$a is my array
Array
(
[0] => class="date-display-single">24-Feb-2013
[2] => 11:35
[3] => AM
)
How do I remove class="date-display-single"> from array[0]?
Several ways... But the simplest one is to do:
$a[0] = str_replace('class="data-display-single">', '', $a[0]);
This simple statement should do exactly that:
$a[0] = substr($a[0], strpos($a[0], '>') + 1);
That said, it all depends on how you ended up with that array in the first place; it seems things can be fixed higher up in the code.
there you are:
$a[0] = str_replace('class="date-display-single">','',$a[0]);
but i would do it in the string, before you explode your date string. no in the array after
Check out unset()
You could try something like:
unset($a[0]);
Try this
str_replace('class="date-display-single">', '', $a[0]);

Categories