Access different arrays with similar keys - php

I have this array
<?php
$themename = "So";
$shortname = "se";
$options = array (
array( "name" => "the_firstname",
"desc" => "The firstname of a person",
"id" => $shortname."_the_firstname",
"type" => "text",
"value" => ""),
array( "name" => "the_lastname",
"desc" => "A persons lastname",
"id" => $shortname."_the_lastname",
"type" => "text",
"value" => ""),
);
foreach($options as $key => $value)
{
echo $value['id']."<br/>";
}
?>
with similar keys for instance the id key.I would like to access the id value of the first array.
Doing this echo $value['id'][0]."<br/>"; or echo $options['id'][0]."<br/>"; isn't helping.
How can i show the value of the first id?.

echo $options[0]['id']; should do the trick on top level, inside the for loop this should work: $value['id']. You don't need the [0] here, since $value contains the first (0) element inside the $options array.

Related

Map two dimensional php array to 1 dimension

I have array inside array:
{
"0" => array("key" => "code", "id" => "4", "value" => "yes"),
"1" => array("key" => "parameter", "id" => "4", "value" => "0"),
"2" => array("key" => "code", "id" => "5", "value" => "no"),
etc...
}
This is what I want to do: I want to have one dimension array in which key would be "id" and value would be "value". However, I need to filter out entries whose key is "parameters". So, in this example, the final array should look like this:
{
"4" => "yes",
"5" => "no"
}
I just can't seem to figure out how to do this. Could you please help me a bit? I tried writing this foreach inside foreach but I just can't wrap my head around how to filter data.
foreach ($settings AS $key => $value) {
$id = null;
$value = null;
foreach ($value AS $key2 => $value2) {
// No idea how to filter out uneccesary entries and save the correct ones
}
$finalArray[$id] = $value;
}
This should do it :
$finalArray = array();
foreach ($settings as $setting) {
if ($setting['key'] != 'parameter') {
$finalArray[$setting['id']] = $setting['value'];
}
}
Assuming all your entries have keys 'key', 'id' and 'value'.
use array_column and array_filter like this, if you want to filter more keys add them to out_keys array :
<?php
$array = [
["key" => "code", "id" => "4", "value" => "yes"],
["key" => "parameter", "id" => "4", "value" => "0"],
["key" => "code", "id" => "5", "value" => "no"]
];
$out_keys = ['parameter'];
$result = array_column(array_filter($array, function($item) use($out_keys) {
return !in_array($item['key'], $out_keys);
}), 'value', 'id');
echo "<pre>";
print_r($result);
output:
Array
(
[4] => yes
[5] => no
)
Assuming $data is your starting array, the code below will output what you want in $result
$result = [];
foreach(array_filter($data, function($el){return $el['key']!='parameter';}) as $el){
$result[$el['id']] = $el['value'];
}
Live demo

Appending an array to a multi dimensional array fails silently PHP?

I am trying to append an array to another one in a multi dimensional array:
This is the multi dimensional array:
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
I has a key which is the master id, and a master item which is an array with a name and another array with the detail (at the first time is empty).
But when I try to add to the $info['master']['detail'] array another array with a detail, like this:
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
Nothing is added... How is that possible?
EDIT: the foreach loops that should add the details to the master:
foreach ($details as $detail)
{
$name = $detail['detail_name'];
$value = $detail['detail_value'];
if ($info['key'] == $detail['id']) {
$info['master']['detail'][] = array("name" => $name,
"value" => $value);
}
}
I'm not sure I understand but when I see your examples, I think it is a problem of index:
Try to replace
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
by
$info = array( 'key' => $row['id'],
'master' => array('name' => $row['master_name'],,
"detail" => array())
);
$info['master']['detail'] = array("name" => "A detail name",
"value" => "A detail value");
and to add a new value :
$info['master']['detail']['foo'] = "A detail foo";

How to get a specific data from array?

Right now I have a problem with retrieving data form arrays, maybe it's really simple (probably it is) but I am struggling wiht it since morning and it appears, that my knowledge about PHP is worth nothing...so I have few arrays:
array( "name" => "Array 1",
"type" => "array"),
array( "name" => "Array 2",
"type" => "whatever"),
array( "name" => "Array 3",
"type" => "whatever"),
array( "name" => "Array 4",
"type" => "array"),
array( "name" => "Array 5",
"type" => "whatever"),
What I need to do is to display 'name' of arrays of the 'array' type, I know I need a foreach loop but how to construct 'foreach ($arrays as $array) {' to get the desired result?
EDIT
Thanks for all the replies, but I tihnk I didn't make myself clear. I need to display "name" only when there is a "type" => "array" present within array, every other arrays' "name" should be omitted.
You'll need to do something like this:
foreach($arrays as $array) {
if($array['type'] == 'array') {
print($array['name']);
}
}
An array_map will do
array_map(function ($v){ if($v['type']=="array"){echo $v['name']."<br>";}},$arr);
OUTPUT :
Array 1
Array 4
Demo
put the arrays into a "container" array first, then you can use that one...
<?php
$data = array(
array( "name" => "Array 1",
"type" => "array"),
array( "name" => "Array 2",
"type" => "whatever"),
array( "name" => "Array 3",
"type" => "whatever"),
array( "name" => "Array 4",
"type" => "array"),
array( "name" => "Array 5",
"type" => "whatever")
);
foreach($data as $array) {
if($array['type'] == 'array') {
print($array['name']);
}
}

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

PHP multidimensional array

Here's a quickie for the pros:
How do I display Value 1, 2, 3 etc as it's in it's third array?
$meta_boxes = array
(
"checkbox" => array
(
"name" => "checkbox",
"title" => "",
"description" => "This is an example of a checkbox field.",
"type" => "checkbox",
"rows" => "",
"width" => "",
"options" => array
(
"1" => "Value 1",
"2" => "Value 2",
"3" => "Value 3"
)
),
$str = '';
foreach($meta_boxes['checkbox']['options'] as $k => $v) {
$str .= $v . "\n";
}
$meta_boxes['checkbox']['options']['1'] will give you the string "Value 1" from the array, and then you can do whatever you want with that value.
You should now be able to figure out how to access the other two.

Categories