如何动态打印multidimensinal数组直到count

时间:2016-12-05 11:41:20

标签: php arrays json multidimensional-array

我有一个JSON值,我从db下面得到

[{"skill_title":["developer","jQuery","HTML"],"skill_marks":["50%","100%","80%"]}]

我正在解码此值,如下所示

$usrskill = json_decode($usrskill[0]->skills,true); 

并且,我得到了以下结果:

    Array
(
    [0] => Array
        (
            [skill_title] => Array
                (
                    [0] => developer
                    [1] => jQuery
                    [2] => HTML
                )

            [skill_marks] => Array
                (
                    [0] => 50%
                    [1] => 100%
                    [2] => 80%
                )

        )

)

我想要的是动态地将所有数据分配给输入字段值,就像我有两个输入字段

<div>
    <input placeholder="Engineer,Doctor,Developer etc." type="text" name="skills[]" value="">
    <input placeholder="Eg. 80%" type="text" name="skillmark[]" value="">
</div>

我想加载此输入字段,直到此结果中出现值

预期结果这就是我希望我能告诉你我想要的东西

<div>
    <input type="text" name="skills[]" value="developer">
    <input type="text" name="skillmark[]" value="50%">
</div>


<div>
    <input type="text" name="skills[]" value="jQuery">
    <input type="text" name="skillmark[]" value="100%">
</div>

<div>
    <input type="text" name="skills[]" value="HTML">
    <input type="text" name="skillmark[]" value="80%">
</div> 

我正在使用foreach循环,但它正在获取非动态的静态数据

foreach ($usrskill as $key => $value) {
    echo $value['skill_title'][0] .' Marks '. $value['skill_marks'][0];
}

2 个答案:

答案 0 :(得分:1)

你的数组$ usrskill是一个元素的数组,这是因为你的JSON。所以你可以采取这个元素,这就是你想要的。 然后你可以查看你的阵列。

The json is an array with one object inside.
$json = '[{"skill_title":["developer","jQuery","HTML"],"skill_marks":["50%","100%","80%"]}]';
//Decode json...
$usrskill = json_decode($json, true);
//... And get the first and only element inside.
$usrskill = $usrskill[0];
//Your two arrays have to have the same length!
$count = count($usrskill["skill_title"]);
//Look over every element and echo the html you want.
for ($i = 0; $i < $count; $i++) {
    echo '
    <div>
        <input type="text" name="skills[]" value="' . $usrskill['skill_title'][$i] . '">
        <input type="text" name="skillmark[]" value="' . $usrskill['skill_marks'][$i] . '">
     </div>
    ';
}

在这里,您可以看到LIVE DEMO(感谢@Faisal

答案 1 :(得分:0)

我认为这将适用于您的上述情况 -

<?php

$test = '[{"skill_title":["developer","jQuery","HTML"],"skill_marks":["50%","100%","80%"]}]';

$usrskill = json_decode($test,true); 

foreach($usrskill as $kk=> $test){ 

    foreach($test['skill_title'] as $kk=> $test1){
        echo '<div>
    <input type="text" name="skills[]" value="'.$test1.'">
    <input type="text" name="skillmark[]" value="'.$test['skill_marks'][$kk].'">
</div>';
    }
}

检查还运行example- http://codepad.org/heNhHeB4