I have an array like this
$data = array(
"some" => "163",
"rand" => "630",
"om" => "43",
"words" => "924",
"as" => "4",
"keys" => "54"
);
How can I get each set's key associated with their values like this:
foreach ($data as $stuff){
$this->$stuff["key"] = $stuff["value"];
}
foreach ($data as $key => $value){
echo "$key => $value\n";
}
foreach($data as $key => $value)
{
// $key and $value variable are available here
// First iteration values would be: $key = "some" and $value = "163"
}
Related
Someone please help me correcting the errors in this code
This was the code where i am trying to find the names of the icecreams in stock
<?php
$flavors = array();
$flavors[]=array("name" => "CD" , "in_stock" => true);
$flavors[]=array("name" => "V" , "in_stock" => true);
$flavors[]=array("name" => "S" , "in_stock" => false);
foreach($flavors as $flavor => $value) {
if($flavor["in_stock"] == true) {
echo $flavor["name"] . "\n";
}
}
?>
You have flat non-associative array, that means you don't need to iterate using $key => $value but just $item.
So in you case the fix is that simple:
https://ideone.com/j7RMAH
...
// foreach ($flavors as $flavor => $value) {
foreach ($flavors as $flavor) {
...
foreach() - foreach will additionally assign the current element's key to the $key variable on each iteration
foreach (array_expression as $key => $value)
statement
Note: You can use any variable it's not necessary to use the variable with name $key
You are using the key for the condition $flavor["in_stock"] and same for the $flavor["name"]. You need to use $value which holding the current iteration array, correct use of foreach for your code is
foreach($flavors as $flavor => $value) {
if($value["in_stock"] == true) {
echo $value["name"] . "\n";
}
}
Why iterate at all? One can just filter an array with a condition:
<?php
$flavors = [];
$flavors[] = ['name' => 'CD', 'in_stock' => true];
$flavors[] = ['name' => 'V', 'in_stock' => true];
$flavors[] = ['name' => 'S', 'in_stock' => false];
$inStock = array_filter($flavors, function (array $flavor) {
return $flavor['in_stock'];
});
print_r($inStock);
$inStockFlavors = array_column($inStock, 'name');
print_r($inStockFlavors);
I have an array similiar to the one below:
array("animal" => array("lion", "fish", "tiger)
And I want to turn into the following in JSON format.
'{"group":"animal","types":["lion", "fish", "tiger"]}'
How do I add the 'labels' such as "group" and "type"?
$array=array();
$array['animal'] = array('lion','tiger','fish');//Your array
echo json_encode(array("group"=>"animal","types"=>$array['animal']));
//Output : {"group":"animal","types":["lion","tiger","fish"]}
Create and format a result array that will allow you to store the datas in the expected format.
<?php
$arr = array("animal" => array("lion", "fish", "tiger"));
$result = array("group" => "",
"types" => array());
foreach ($arr as $key => $value)
{
$result["group"] = $key;
$result["types"] = $value;
}
var_dump(json_encode($result));
output :
string(50) "{"group":"animal","types":["lion","fish","tiger"]}"
If you have many groups, the loop might need to be changed a bit :
<?php
$arr = array(array("animal" => array("lion", "fish", "tiger")),
array("colors" => array("red", "green", "blue")));
$finalResult = array();
foreach ($arr as $item)
{
foreach ($item as $key => $value)
{
$result["group"] = $key;
$result["types"] = $value;
$finalResult[] = $result;
}
}
var_dump(json_encode($finalResult));
Output :
string(102) "[{"group":"animal","types":["lion","fish","tiger"]},{"group":"colors","types":["red","green","blue"]}]"
i am in need of bit direction here for renaming my inner child keys who inner depth is unknown. Original array is parent child multidimensional array created via id and parent_id relation. Here's a one example of array
$testArray = array (
"name" => "Test name",
"someValue1" => 834.69,
"someMoreValue" => 33.4,
"someCode" => 6668,
"child" => array
(
array
(
"name" => "Some name",
"someValue1" => 471.05,
"someMoreValue" => 18.84,
"someCode" => 7064,
"child" => array
(
array
(
"name" => "Yet another name",
"someValue1" => 438.62,
"someMoreValue" => 17.56,
"someCode" => 7065
),
array
(
"name" => "Da name",
"someValue1" => 4444,
"someMoreValue" => 44,
"someCode" => 7044
)
)
),
array
(
"name" => "name",
"someValue1" => 2222,
"someMoreValue" => 22,
"someCode" => 7022
)
)
);
here's my trying so far, i am able to rename the first level of childs only.
function keyprefix($keyprefix, $keyprefix2, Array $array) {
foreach($array as $k=>$v){
$array[$keyprefix.'-'.$k.'-'.$keyprefix2] = $v;
unset($array[$k]);
}
return $array;
}
function test($array) {
$newArr = array();
foreach ($array as $key => $value) {
// $newArr[] = is_array($value) ? test($value) : $value;
// $newArr[] = is_array($value) ? $array : array_merge( keyprefix("$name","Alt Danışman", $array[$key]) );
$index = 0;
$name = $array['name'];
if (is_array($value)) {
//if (is_array($value)) {
// test($value);
//}
$newArr[$key] = array_merge(
keyprefix("$name","Under Child", $array[$key])
);
}
else {
$newArr[$key] = $value;
}
}
return $newArr;
}
echo highlight_string(var_export(test($testArray), true));
Any ideas on how I can approach this? I feel that I am close just need a little guide in the right path. I have seen many examples of stack-overflow etc but need some help. I know recursion is not my best skill yet.
function TryRenameChildren(array $array)
{
if(isset($array['child']))
{
$array['child'] = keyprefix($array['name'], 'prefix2', $array['child']);
foreach($array['child'] as $key => $value)
if(is_array($value))
$array['child'][$key] = TryRenameChildren($value);
}
return $array;
}
$testArray = TryRenameChildren($testArray);
How Do I access the innermost array? the grade is giving me a Notice: Array to string conversion in /scripts/array.php on line 34
grade: Array
$data = array();
$data[0] = 78;
$data[1] = 34;
$data[2] = 87;
$student = array(0 => array(
"Stdno" => "212",
"name" => "Lorem Ipsum",
"subject" => "Networking",
"grade" => $data
),
1 => array(
"Stdno" => "212",
"name" => "Jimmy Shu",
"subject" => "Informatics",
"grade" => $data
),
2 => array(
"Stdno" => "212",
"name" => "Amet Dolor",
"subject" => "Discrete Combinatorics",
"grade" => $data
)
);
foreach ($student as $key => $value) {
foreach ($value as $key => $value) {
echo "<b>{$key}</b>: {$value}";
echo "<br />";
}
echo "<br />";
}
First of all, you should really not use $key and $value again (in fact, I thought foreach ($value as $key=>$value) didn't work).
Assuming you want to echo the $data element at the same position than in your $student array (i.e. echo $data[0] for $student[0]), you should use the first key :
foreach ($student as $key => $value) {
foreach ($value as $key2 => $value2) {
echo "<b>{$key2}</b>: ";
if ($key2 == 'grade')
echo $value2[$key];
else
echo $value2;
echo "<br />";
}
echo "<br />";
}
First, just a comment please avoid using same keys on foreach. like in your $value.
To fix your issue, it clearly says, it's an array but you try to echo it, you could try to use this instead.
echo "<b>{$key}</b>: " . json_encode($value);
As stated by #roberto06 you should avoid using same variables for cycles that are nested. Those variables will be overwriten by new values.
To the question:
You could check wether $value is string or array
is_array($val) || is_string($val)
based on result you could write another foreach cycle or print string.
in your second foreach you are foreaching this array:
array(
"Stdno" => "212",
"name" => "Lorem Ipsum",
"subject" => "Networking",
"grade" => $data
)
so the (second) $key will be "Stdno", "name", "subject", "grade"
and values will be "212", "Lorem Ipsum", "Networking" (those are strings) and $data (this is array)
to print this array, you need to create new foreach and use it only when $key == "grade" or use implode on it:
if($key == "grade"){
$i = implode(', ', $value);
//print or something
}
I'm retriving data from mysql. in my php I've got 2 arrays set
$main =array(); //tostore retrived data
$list =array('instock' => 'output1', 'item' => 'output2'); //existing key values and new key value to be replaced
How do I replace the keys with custom keys for each output? exmpale: custom keys output1,output2
current output
[{"instock":"yes", "item":"ch00024"},{..}]
Expected output
[{"output1":"yes", "output2":"ch00024"},{..}]
This is what I have tried so far. But does not work.
$main =array(); //tostore retrived data
$list =array('instock' => 'output1', 'item' => 'output2'); //replace key values
foreach ($result as $key => $value){
$main[ $list[ $key ] ] = $value;
}
echo json_encode( $main );
I get an error Undefined offset: 0. It points to this line $main[ $list[ $key ] ] = $value;
EDIT
This is a screen capture from my console
var_dump():
array(5) {
[0]=>
array(2) {
["instock"]=>
string(3) "yes"
["item"]=>
string(6) "it0215"
}
[1]=>
array(2) {
["instock"]=>
string(3) "yes"
["item"]=>
string(6) "it0381"
}
so on...
Your code works! The issue is in $list array you need define all keys in $result otherwise you need to check if there is that key in $list array.
$result =array(
'instock' => 'yes',
'item' => 'ch00024',
'color' => 'blue',
'price' => 100
);
$main = array();
$list = array('instock' => 'output1', 'item' => 'output2');
foreach ($result as $key => $value){
if (!empty($list[$key])) {
$main[$list[$key]] = $value;
}
}
echo json_encode($main);
Edit
Because you are access 2 dimensional array, so you need an extra loop to go through all items
$result = array(
array (
'instock' => 'yes',
'item' => 'it0215'
),
array(
'instock' => 'yes',
'item' => 'it0381'
)
);
$main = array();
$list = array('instock' => 'output1', 'item' => 'output2');
foreach ($result as $item){
foreach ($item as $key => $value) {
$main[$list[$key]] = $value;
}
}
echo json_encode($main);
The output is
{"output1":"yes","output2":"it0381"}
But In case you want to get all items with key replacement in new array. You should do something like this:
foreach ($result as $index => $item){
foreach ($item as $key => $value) {
$main[$index][$list[$key]] = $value;
}
}
echo json_encode($main);
The output is:
[
{"output1":"yes","output2":"it0215"},
{"output1":"yes","output2":"it0381"}
]
try to this code
$flippedList = array_flip($list);